Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
406 views
in Technique[技术] by (71.8m points)

javascript - Will setInterval cause browsers to hang?

A couple years ago I was warned against using setInterval for long periods of time as it supposedly would cause the browser to hang if the called function ran longer than the designated interval, and would then not be able to catch up:

setInterval( function(){
  foo = 'bar_' + i++;
}, 1 );

Now, I'm aware that adding lots of code in a loop could cause the browser to hang anyway, and that blocking code like alert, prompt, and confirm will stop the code in it's tracks, but is there any good reason to avoid setInterval?

Note: I am aware of how to do recursive setTimeout calls (as that's what I've been using), this question is my trying to figure out if it's still worth using them, or whether setInterval can be used safely.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason setInterval is bad is because it will try to execute the code every X MS regardless of what's going on in the thread. So if you have:

setInterval( complexFunction, 1 ); // complexFunction takes >1 MS to complete

...you may end up with setInterval trying to re-execute several times before even its own code is complete! However, you can use setTimeout similarly and avoid this problem:

setTimeout( complexFunction, 1 );

function complexFunction() {
  // complex code
  setTimeout( complexFunction, 1 );
}

...now complexFunction will only call itself again once its own code is complete, so if its own code takes longer than 1 MS to complete you won't have any backlog to deal with like you would with setInterval


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...