Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript set interval run as separate thread?

Tags:

javascript

I want to use a timer as a fallback in case I end up in an infinite loop. It seems that set interval is the right way to do this. However, it's not working for me.

From my research, it seems like setInterval should run in a separate thread in the background, but I don't see it.

Why is this behavior happening? And how do I solve this?

var time = 0;
window.setInterval(function(){time++;}, 1000);
while (true) {
    //stuff done
    if (time >= 5) {
        break;
    }
}
like image 578
user1811367 Avatar asked Nov 22 '12 01:11

user1811367


1 Answers

Browser javascript runs in a single thread. So if you perform something that takes too long - it will freeze browser.

See John Resig article for further details: http://ejohn.org/blog/how-javascript-timers-work/

After you read that article you'll get that your setInterval callback queued to be run in 1000ms after now but only after the current code is finished. It cannot finish though, because of the infinite loop.

like image 195
zerkms Avatar answered Nov 12 '22 15:11

zerkms