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.
Related
I have a 'for' loop wich have to loop around 10000000000 times so that i get the disered result.
However, it ends up all the time freezing the browser ...
It's not like that 'for' is working infinitly but as i told, it's very long
Is there some way to solve my problem with javascript or i should use another language ?
In a compiled language and if you do virtually nothing in the loop, you can achieve 1,000,000,000 iterations a second on a desktop processor. So your loop would take 10 seconds.
If your Javascript environment is interpreted (and not compiled), you probably won't get more than 10,000,000 iterations and your loop will take 1000 seconds (16 minutes).
If you additionally have somewhat more expensive operations within the loop (and Javascript is likely to allocate memory for simple operations, which is expensive), you're in the order of 1,000,000 iterations per seconds and your code takes 10,000 seconds (close to 3 hours).
You might want to think about a better algorithm...
The issue that you are seeing is because javascript is single threaded in the browser. Your for loop is holding on to the thread for the entire time that it is running. The problem is that this thread also handles interactions with the interface. There may be other possibilities, but the two ways that I can think of to fix this would be:
Use a Web Worker (docs), this solution will not work for older browsers though
If possible, break your loop into smaller chunks that can be ran using setTimeout. After each chunk is processed, use setTimeout to schedule the next chunk to be processed in say 100ms. You will need to play with the numbers, but that should free up the thread so that it can respond to events. This will make the calculation take longer but should make it so the browser doesn't freeze up.
Don't do it. To run this kind of Javascript code in a browser makes no sense. If you really want to do this on the client side, you should consider writing some kind of browser extension, where you have more control on the CPU and local storage.
You might want to separate that loop in smaller chunks and run them sequentially, with an appropriate progress system. If you are talking about a loop, a multithreaded system will not help you, assuming the result n+1 is based on the n result.
Consider using a server-side script with a queue or job mechanism and just push notifications to the client. As Teemu said, the time (even in a fast paced situation) is huge.
It is more of a hypothetical question. There is sometimes a possibility of a javascript code entering an infinite loop and blocking everything specially in early stages of development. I know the best solution would be to code so that such a situation never arises but what if in a certain case it is impossible to write a fullproof code (maybe because we don't have control on the input or something else).
Is there any way we can programmatically determine when a code is in an infinite loop and terminate it?
Maybe running the pieces of code where such a thing could happen in a separate thread or in a child process synchronously and determining when that thread/process is in an infinite loop.
How could one go about doing that? Is it possible to determine when a thread (either main or child) is in an infinite loop by determining the CPU usage by that thread alone?
Based on the discussion had in comments below I realise that identifying a blocking infinite loop would be impossible on the basis of tracking repetitive execution of similar statements and high resource utilization alone. So I think that the solution lies in a combination of both. But that brings as back to our earlier problem. How can we gauge the CPU usage by a script?
For simple loops you can use approach used here . It uses path based approach to detect infinite loop. Statements are considered as nodes of graph.
You can also see this paper. They have implemented run time solution for java program.
Given there are no other viable/sophisticated solutions proposed, a low-tech solution is to just use a counter and abort if it reaches an absurdly high number.
This requires manual coding effort, but can be useful for debugging an infinite loop when you know it is already happening.
var count = 0
while(true){
if(count++>100000){
//assume infinite loop, exit to avoid locking up browser while debugging
break;
}
}
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.
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.
I am trying to run a script, which is intense(that is lot of loops etc.). When I am trying to call this method in loop, I am getting an error:
"The JavaScript operation is blocking the normal operation of IE. Do you want to stop running the script?" Yes No.
Is there something I am missing? I have seen worse scripts running just fine.
If your script does that, you might want to re-engineer your code.
If your code really need to loop for that long you will be dealing with some timeouts in your script to stop every time you think is necessary to avoid this "behavior"...
I recommend to check this post JavaScript and Threads