1

How does one write an infinite loop in javascript that won't crash your browser. I have found two things on the internet regarding infinite loops in javascript...

for(;;){}

and...

while(true){}

the problem with both of these is that the crash my computer... I thought you were able to just put...

Loop;

at the end of the code and it would infinitely loop through the code, but I was wrong, what is the proper way to loop through code infinitely that will not crash my browser?

Joshua Reid
  • 61
  • 1
  • 9

1 Answers1

4

If you need to write some Javascript code that takes a long time (up to and including "forever") you should move it out of the main Javascript content and into a WebWorker.

var myWorker = new Worker('worker.js');

This allows you to load the script in worker.js and execute it in a separate context that runs in parallel.

If you just need something to run once and while until the user exits the page (or closes the browser) then just use setInterval:

var intervalID = window.setInterval(myCallback, 500);

function myCallback() {
  // Your code here
}
John Wu
  • 50,556
  • 8
  • 44
  • 80