JavaScript functions setTimeout() and setInterval() are sometimes not working - javascript

My own Google Chrome extension stops working after some time, because setTimeout() is not working in some cases.
Therefore the background script is not sending a message to the content script after some necessary delay.
I have found this problem by writing many console.log() statements.
As a solution i thought about using setInterval() until the message is sent to the content script:
var timer = setInterval(function() {
clearInterval(timer);
// Sending a message to the content script
}, 3000);
My code before, during and after setInterval() is quiet long, so i hope this code snippet is somehow enough.
Does anyone know in which cases these Timeouts or Intervals do not start?
Or are there any similar options i could use?
I have thought about using the Chrome Alarms API instead, but alarms can only be used once every minute and the minimum delay is one minute if i am not mistaken.

I never experienced any issue of setinterval or settimeout stops working. I guess there might be an issue in your code. If you are sure about the bug you should make a demo project and report bug on github.

Related

How to wait for PyScript to be fully initialised (environment included)?

Good morning,
I would like to wait for a message (logged to my browser's console by a script I imported in my HTML tag) to be logged and then do an action in JavaScript.
For example, I'd like to wait for "ABCD:READY" to be printed in the console to use a function called finallyStart().
Is it possible ?
I thought I only needed to read the content of stdout to do this, but it looks like browsers don't call their console output stdout...
I also tried to find an answer in stackoverflow, but none of the posts I found were similar to the one I'm currently writing.
I'm a novice when it comes to JS in browsers (I've only used NodeJS for back-end), so thanks in advance for your help !
I faced the same problem and eventually came up with this hacky but working solution.
First create a dummy element in your html.
<div hidden id="start"></div>
Make an event for that element call a function in your js script.
document.getElementById("start").onclick = main;
Then trigger that event manually from your python script.
from pyscript import Element
Element("start").element.click()
No python code can execute until pyscript has finished initializing, so this seems like a reliable strategy. It would be even better if you could call the main() function directly from your python script, but i didn't have the patience to figure that out.
p.s. For some reason it takes a few seconds after pyscript has officially initialized for the code to kick off (at least in my test). I have no idea what's happening during that time, though i suppose it doesn't make a big difference to the already hefty build time.

Is it possible to execute javascript from console between pages?

I am trying to solve this issue and can’t seem to find any answers on the web or anywhere. The task is simple. I am using console in Chrome and I am trying to execute Javascript code that will execute the code between pages. As a simple example trying to navigate and pause between pages seems like impossible task.
var increment = 1;
var miliseconds = 2500;
setTimeout(function () {window.open('www.google.com', '_self');}, miliseconds * increment);increment++;
// Do something or grab values on this page
setTimeout(function () {window.open('www.yahoo.com', '_self');}, miliseconds * increment);increment++;
// Do something or grab values on this page
setTimeout(function () {window.open('www.cnn.com', '_self');}, miliseconds * increment);increment++;
Tried event listeners and no luck. Any help?
Unfortunately this is not possible. The console's environment will clear every time you navigate. The most you can do is preserve logs, but that will not allow you to continue executing JS defined on the previous page.
The only way I know of to persist values accross pages is to use the window.name variable which will remain accross different pages, but this is pretty hacky.
If you're looking for something a bit more permanent, I would recommend writing a chrome plugin instead.

Keep and run code in debugger every time the page is reloaded

I have a function that will reload the current page after a period of time. I want this function to run automatically every time the page is reloaded (using the debugger).
function reloadPage() {
window.location.reload(false);
}
setInterval(reloadPage,3000)
The problem is that every time the page is reloaded, the code in the debugger will be cleaned and the function will not be called. How to fix this?
A very simple solution: Rather than putting the Javascript into the console, consider putting it in your application but disabling it when you're not debugging.
For example, you could have a GET parameter in your URL that, when present, triggers the function. A good explanation of how to retrieve a GET parameter in Javascript is at How to retrieve GET parameters from javascript?
An even simpler alternative would be to simply leave this code commented out, and comment it in when you want to debug. (This is not a good practice and I will scold you for it during code review, but it is a real thing that real people do, and it has the advantage of being easy and working.)
-
An alternative: You could detect when the console is open, and only run your code when the console is detected (though this would annoy power users like me who tend to always have developer tools open). It's not trivial to detect, but there's a library you can use: https://github.com/zswang/jdetects

CSS Animations stall when running javascript function

Let's say I have this javascript function:
function pauseComp(ms) {
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < ms);
}
and a css3 animation (for instance, <i class="icon-spinner icon-spin"></i> from the new font-awesome 3). When I run the javascript function above, it stops the spinner while the function is running. See what I'm talking about here. Basically, javascript stops css animations, and I'm wondering why, or if anyone else has noticed this/found a workaround. I've tried putting it in a setTimeout(fn,0), where fn is the long process, but then realized why that will also not work (js is not multithreaded). Anyone seen this happening?
Update: Interestingly, it looks like this isn't as much of a problem in Safari, although interaction with the browser interface is still being affected.
A browser page is single threaded. Updating the UI happens on the same thread as your javascript program. Which also means that any animation will not draw new frames while Javascript code is being executed. Typically, this is no big deal because most JS code is executed very quickly, faster than a single animation frame.
So the best advice is simply this: Don't do that. Don't lock up the JS engine for that long. Figure out a cleaner way to do it.
However, if you must, there is a way. You can get an additional thread via HTML5's Web Workers API. This isn't supported in older browsers, but it will allow you to run some long running CPU sucking code away from the main webpage and in it's own thread, and then have it post back some result to your page when it's done.

Javascript debugging

I have recently started to tinker with Project Euler problems and I try to solve them in Javascript. Doing this I tend to produce many endless loops, and now I'm wondering if there is any better way to terminate the script than killing the tab in Firefox or Chrome?
Also, is firebug still considered the "best" debugger (myself I can't see much difference between firebug and web dev tool in safari/chrome ).
Any how have a nice Sunday!
Firebug is still my personal tool of choice.
As for a way of killing your endless loops. Some browsers will prevent this from happening altogether. However, I still prefer just going ctrl + w, but this still closes the tab.
Some of the other alternatives you can look into:
Opera : Dragonfly
Safari / Chrome : Web Inspector
Although, Opera has a nice set of developer tools which I have found pretty useful. (Tools->Advanced->Developer Tools)
If you don't want to put in code to explicitly exit, try using a conditional breakpoint. If you open Firebug's script console and right-click in the gutter next to the code, it will insert a breakpoint and offer you an option to trigger the breakpoint meets some condition. For example, if your code were this:
var intMaxIterations = 10000;
var go = function() {
while(intMaxInterations > 0) {
/*DO SOMETHING*/
intMaxIterations--;
}
};
... you could either wait for all 10,000 iterations of the loop to finish, or you could put a conditional breakpoint somewhere inside the loop and specify the condition intMaxIterations < 9000. This will allow the code inside the loop to run 1000 times (well, actually 1001 times). At that point, if you wish, you can refresh the page.
But once the script goes into an endless loop (either by mistake or design), there's not a lot you can do that I know of to stop it from continuing if you haven't prepared for this. That's usually why when I'm doing anything heavily recursive, I'll place a limit to the number of times a specific block of code can be run. There are lots of ways to do this. If you consider the behaviour to be an actual error, consider throwing it. E.g.
var intMaxIterations = 10000;
var go = function() {
while(true) {
/*DO SOMETHING*/
intMaxIterations--;
if (intMaxIterations < 0) {
throw "Too many iterations. Halting";
}
}
};
Edit:
It just occurred to me that because you are the only person using this script, web workers are the ideal solution.
The basic problem you're seeing is that when JS goes into an endless loop, it blocks the browser, leaving it unresponsive to any events that you would normally use to stop the execution. Web workers are still just as fast, but they leave your browser unburdened and events fire normally. The idea is that you pass off your high-demand tasks (in this case, your Euler problem algorithm) to a web worker JS file, which executes in its own thread and consumes CPU resources only when they are not needed by the main browser. The net result is that your CPU still spikes like it does now, but your browser stays fast and responsive.
It is a bit of a pest setting up a web worker the first time, but in this case you only have to do it once. If your algorithm never returns, just hit a button and kill the worker thread. See Using Web Workers on MDC for more info.
While having Firebug or the webkit debuggers is nice, a browser otherwise seems like overhead for Project Euler stuff. Why not use a runtime like Rhino or V8?

Categories

Resources