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
1.1k views
in Technique[技术] by (71.8m points)

javascript - setTimeout not working inside infinite loop

    while(true){
        window.setTimeout(function() {
            myMethod()
        }, 15000);
        }
        function myMethod() {
            alert("repeat");
        }

Above piece of code is written to execute mymethod infinitely but in certain intervals but once I run the code my browser hangs and the repeat pop up generates constantly but the time here is 15 secs. I wanted to avoid setInterval so using this technique for my purpose.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Javascript is single threaded (with the exception of web workers, but that is irrelavent to this example so we will ignore it). What this means is that setTimeout actually does is schedules some code to be executed some time in the future, after at least some amount of time, but only when the browser has stopped whatever else it was doing on the rendering thread at the time, which could be rendering html, or executing javascript.

So, the code in the setTimeout can't execute until the while loop (and whatever code contains it) finishes and returns control back to the browser. But it is an infinitely loop, so control is never returned to the browser and the code in the setTimeout is never executed.

In fact, a common idiom in javascript is to use a setTimeout with a timeout of 0 (or possibly 1) so that some code will be executed as soon as possible after the code for the current event has executed, and typically after the browser has rendered any html changes that were made by javascript.

I don't know what your exact use case is, but you can probably do what you want either using a setInterval (which is like setTimeout but is called repeatedly at an interval), or by calling setTimeout inside the function in the setTimeout to achieve an infinite loop with recursion, but letting the browser perform other tasks in between iterations.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...