How to fix firefox stop javascript when not responding - javascript

I'm currently create a javascript that run a loop forever. However, after a few hours my script stop working, it asks me to continue or stop script. Is there anyway to fix this or use some automation tools to restart firefox and run the javascript again. Because most of time I away from keyboard

id strongly recommend not using any kind of infinite loop - doing so would be just asking for trouble. instead you want to look into using javascript's setTimeout() and/or setInterval() functions... allowing you to specify a block of code to run every X milliseconds
you can find the docs here
setTimeout()
setInterval()

To prevent the long running javascript prompt, you need to occasionally let javascript process other events. The classic way to do this is like this is using setTimeout().
function doNextChunkOfWork() {
// do some work here
if (moreWorkToDo) {
setTimeout(doNextChunkofWork, 1);
}
}
Using the setTimeout() lets the javascript engine get back to its event queue and process other events and thus prevents the long running script warning.
If you explained what you're really trying to do, we might be able to suggest even better options. If you're doing some sort of infinite loop, javascript in a browser is meant to be an event-driven environment where the usual mechanism is to create event handlers and let events trigger code to run. It is not meant for infinite loops polling for something.

Related

Is it possible to implement a sleep() in javascript?

This is a duplicate question. It has been asked many times before, with dozens of answers, some of them rated very highly. Unfortunately, as far as I have been able to tell, every single one of those answers is a variant of "You don't, it's bad programming practice. Use setTimeout instead".
This is Not. An. Answer!
There are some use cases - rare but they exist - where you might want the entire page's execution to halt for a second or two, and I find it very frustrating that nobody seems interested in answering the actual question. (have a look at the comments here for some examples).
I am sure it's possible to halt javascript executing; for instance, if I use firebug to insert a breakpoint, then the execution stops when it hits that point. So, firebug can do it. Is there some way that the program can halt execution of the current thread until some timeout occurs?
Just some thoughts: How does firebug do it? Is there some browser-specific method? Is it possible to trigger a stop, without specifying a timeout to continue? Could I programmatically insert a breakpoint, or remove one? Could I get a closure representing the current thread to pass to setTimeout?
I don't have a specific use case in mind; I am just looking for advise from someone who knows the browser/javascript design better than me, as to how this can most effectively be done.
So far, I have come up with only one solution:
endtime=Date.now()+1000;
while(Date.now() < endtime)
$.ajax(window.location.origin,{'async':false});
This appears to work. The problem with it is, it makes hundreds of excess requests. I would replace the location.origin with something like mysite/sleep?delay=X and write a server side script to provide the delay, which would but it down to one, but the whole thing still seems really hacky. There must be a better way to do this! How does the jquery.ajax function manage it? Or is there a busy-wait buried in it somewhere?
The following do not answer the question and will be downvoted, just because I am sick of seeing pages of answers that completely ignore the question in their rush to rant on the evils of sleep:
Sleep is evil, and you should do anything it takes to avoid needing it.
Refactor your code so that you can use setTimeout to delay execution.
Busy-wait (because it doesn't stop execution for the duration of the sleep).
Refactor your code to use deferred/promise semantics.
You should never do this, it's a bad idea...
... because the browser has been, traditionally, single-threaded. Sleeping freezes the UI as well as the script.
However, now that we have web workers and the like, that's not the case. You probably don't need a sleep, but having a worker busy-wait won't freeze the UI. Depending on just how much you want to freeze a particular thread, I've seen people use:
endtime = Date.now()+1000;
while (Date.now() < endtime)
or, curiously (this was in an older but corporate-sponsored analytics library):
endtime = new Date().getTime() + 1000;
while (new Date().getTime() < endtime)
which is probably slower. If you're running a busy wait, that doesn't necessarily matter, and allocating objects probably just burns memory and GC time.
Code using promises or timeouts tends to be more modular, but harder to read (especially when you first learn async techniques). That's not an excuse for not using it, as there are definite advantages, but maybe you need everything to stay synchronous for some reason.
If you have a debugger running and want some chunk of code to pause itself (very useful when you have a bunch of nested callbacks), you can use:
function foo() {
do.someStuff();
debugger;
do.otherStuff();
}
The browser should pause execution at the debugger statement. The debugger can almost always pause execution, because it is in control of the VM running the code; it can just tell the VM to stop running, and that ought to happen. You can't get quite to that level from a script, but if you take source as text (perhaps from a require.js plugin), you can modify it on the fly to include debugger statements, thus "programmatically inserting breakpoints." Bear in mind that they will only take effect when the debugger is already open, though.
To capture the state of a "thread" and persist it for later use, you may want to look into some of the more complicated functional programming concepts, particularly monads. These allow you to wrap a start value in a chain of functions, which modify it as they go, but always in the same way. You could either keep simple state (in some object), or record and reproduce everything the "thread" may have done by wrapping functions in functions. There will be performance implications, but you can pick up the last function later and call it, and you should be able to reproduce everything the thread may have done.
Those are all fairly complicated and specific-use solutions to avoid just deferring things idiomatically, but if you hypothetically need them, they could be useful.
No, it is not possible to implement a sleep in javascript in the traditional sense, as it is a single-threaded event based model. The act of sleeping this thread will lock up the browser it is running in and the user is presented with a message either telling them the browser has stopped responding (IE) or allowing them to abort the currently running code (Firefox).

Pause all javascript

I have been working on writing a library of code for my future projects. One of the functions I've been working on is a pause function. So far I have no problem with the errors reporting that the script is running to long even on pauses as long as 10 seconds. This is to primarily keep malicious users busy, it works well when you set a very long time. I was wondering if there are any errors that I should look out for that I might face?
Here's the code...
pause = function(a) {
var b = new Date().getTime();
e = false;
function wait() {
d=10;
for(i=0;i<d;i++) {
d++;
var c = new Date().getTime();
if(c-b>=a) {
e = true;
break;
}
if(d>1000000) {
break;
}
}
}
wait();
if(e==false) {
pause(a-(new Date().getTime()-b));
}};
You never ever want to do this sort of thing in Javascript. As you have noticed, the browser will complain about your script taking too long. Furthermore, this will take much more energy than necessary which is important for mobile devices with limited battery capacity.
Instead, use the standard setTimeout() function to run code at a later time.
Javascript already has a way to do that. Use setTimeout() and pass it an anonymous function with the continuation of your operation. The second argument is the delay in milliseconds.
Example:
setTimeout(function(){ alert('hello'); }, 2000);
As I've said in my comments so far, trying to run semi-infinite loops in javascript is never a good idea.
Here are some of the issues to watch out for:
If you don't return to the browser event loop by finishing your javascript thread of execution after some period of time, the browser will stop and prompt the user to kill the javascript in that browser window.
Your code uses a bunch of undeclared variables which makes them implicit global variables. Since they have common names, they could easily interfere with other code.
Because javascript is single threaded, while your loop is running, no other browser events for that window can run rendering the browser window essentially frozen. Users will think it is hung. Patient users might wait longer to see if it completes. Impatient users will kill the browser window.
Essentially what you're trying to do is a denial-of-service attack on a user's browser. You may not like what they're doing to your web page, but attacking them back does not seem appropriate. Much better to just block access to your page in a browser-appropriate way rather than a browser-attacking way.
Suggestions:
If what you're really trying to do is just render your page unuseful in some circumstances (you still haven't explained why you're trying to do this or what condition triggers your desire to do this), then it might be better to just make the page unuseful or informative without trying to kill the browser. You could do that by:
Just hiding everything in the DOM so the window goes blank.
Remove all DOM elements so the window goes blank.
Put a transparent layer over the whole window so that no input events can get to the page elements, but the visuals stay there. You could add a message to that window.
Replace the contents of your page with an appropriate message.

Why does this while loop make the browser crash?

I'm trying to compare the differences between similar snippets with javascript and C++. Here's my snippet:
var i = 0;
while (i<=10)
{
document.write('Hello<br />');
//i++;
}
With C++, if I write an equivalent snippet, I recall the console prints that line forever until I enter Ctrl + C. However, with Javascript, if I try to open the browser, it would crash. Does it have to do with the browser trying to load that "Hello" line forever until I force quit?
You can't stop the process in javascript like you can do in C++.
In javascript most browsers even have a limit of the number of loop execution and most browsers (if not all) will crash with those type of loops.
Just no infinite looping in JS
The browser probably wouldn't crash, but it would detect that your script had gone awry and ask you if you wanted to terminate the script. If you answer no, then it would loop forever and render the browser unusable.
The browser will loop forever, you can stop it the infinite iterations thought just by stopping the js usage in the browser. For example in firefox choose (deactivate javascript)
There's the only way how to stop java script in browser but I'm sure there is many ways to do it.

Asynchronously running C++ and JS code in V8

I'm currently experimenting with embedding V8 in a project of mine. Since I use libev for listening to sockets and events and want to be able to script events with JS I would want to be able to just run v8 for a short while and then jump back to C++ to check for events and such and then go back to running JS-code. Since I haven't done much script embedding earlier I'm sure there are some clever way that this usually is done in so all ideas are appreciated.
The cleanest way I found of doing this is to create setTimeout and clearTimeout functions within JS. setTimeout creates a ev::Timer which has a callback that gets called after a certain amount of time. This makes it so that when you call a JS function you continue to execute that until it returns, but that function can set a number of timeouts which aren't called until after you exit the current JS and there hasn't happened any other libev events during the execution, in that case those are handled first (in C++). The limitations of this method is that the coder who writes JS has to remember to not write functions that goes into eternal while-loops or similar. A loop is instead done like this:
function repeat() { setTimeout(repeat, 0); }

Fooling the Internet Explorer Javascript engine into letting a script run

I'm repeatedly coming into troubles with Internet Explorer's "This script is taking too long to run, would you like to continue?" messages. I am wondering if anyone is aware of a clever way to trick the JS engine into keeping quiet? Based on some searching I did, I found that the engine monitors states it thinks potentially could be infinitely looping, so I thought maybe I could add some logic to change up the execution every once in a while to fool it into leaving it alone, but no luck. I also tried breaking up a longer loop into several shorter ones, but that hasn't helped. Specifically the code that is currently causing issues is the expansion of nodes in a tree structure. The code is looping over the current nodes and expanding each. It's a trivial thing to write in Javascript, but I can't allow these timeout errors, so I think my only option might be to request pre-expanded view data via AJAX. I'm currently working in a DEV environment with a small(ish) data set and I know this will not fly in other environments. Has anyone managed to suppress these warnings?
Using setTimeout
A good way is simulating threaded execution using setTimeout() function calls. This requires splitting your whole processing into smaller parts and queueing them one after another. Timeouts can be set quite close to each other but they will run one by one when each of them finishes execution.
How about spacing it using a series of events. So a loop occurs sends an event, listener to event triggers and does a loop. etc..?
Why not break your function into a series of steps and queue them up using jQuery?
http://api.jquery.com/queue/
Have you tried making it output something every once in a while? It might be that it just checks for output and if there hasn't been any in x seconds, it assumes you're in an infinite loop.
If outputting works, you could try something like adding and then immediately deleting something really small (like an empty <span>).
A very common solution for this problem is to use setTimeout function.
The way you do it is that you separate the process into smaller pieces a then execute those pieces one after another using the setTimeout function.
I think this http://www.julienlecomte.net/blog/2007/10/28/ should help you.
There is also another option introduced by HTML5 WebWorkers.
This new standard should allow you to execute long running tasks in a separate thread and then report any results in a callback.
You can read about it here robertnyman.com/2010/03/25/using-html5-web-workers-to-have-background-computational-power/
Unfortunatelly, it is not supported by IE according to html5demos.com/
I think the timeout is more based on the number of statements than timing or heuristics. You could go a long way to increasing the amount your code can handle before triggering the warning by optimizing your code for simple things -- especially if you are using helper APIs on another library like jQuery. For example, change this:
$.each(arr, function(value) {
// do stuff
});
to this:
for (var i = 0, l = arr.length; i < l; i++) {
var value = arr[i];
// do stuff
}
Another easy one -- cache access to fields. If you have two instances of "foo.bar", store the result in a variable and use it, wherever that makes sense.
Obviously I have no idea what your code looks like, but I bet you could do a lot to improve it as these little things really add up when you're talking about this timeout problem.
I managed to do this by using prototypes Function#defer method, which is essentially the same as using the setTimeout method. Thanks everyone!

Categories