javascript - setInterval
阿神
阿神 2017-06-12 09:24:04
0
2
699

The execution time of executing this code on a Windows browser is very different from that of executing this code on a Mac.
This method executes output every 1ms. Why are there differences between windows and mac? It's obviously slower on mac.

var time =0;
var interval = setInterval(function(){
    time++;
    console.log("time="+time);
    if(time===100){
        clearInterval(interval);
    }
},1);
阿神
阿神

闭关修行中......

reply all(2)
女神的闺蜜爱上我

Yes, many times settimeout and setinterval are not particularly accurate. The reason is that js is single-threaded

The callback function of setInterval is not executed immediately after the timeout, but will be executed after the system computing resources are idle

The next trigger time will not start until the setInterval callback function is executed

So if the calculation performed within setInterval is too time-consuming

Or if there are other time-consuming tasks being executed, the timing of setInterval will become increasingly inaccurate and the delay will be severe.

学霸

Let me give you a simple example:

<script type="text/javascript">
        setTimeout(function(){
            console.log('a');
        } , 0);
        console.log('b');
</script>

Guess who will execute it first? Although we say js is single-threaded, the browser can control multiple threads. When we set setTimeOut, the browser will actually call a thread, and this thread is called Event Loop. Let this The thread helps us execute it, while the main thread continues to execute the following code. This is the asynchronous mode that we often talk about.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template