关于setTimeout()和setInterval()需要记住的事项
let i = 1; setTimeout(function run() { console.log(i); i++; setTimeout(run, 100); }, 100);
Compare the above example to the following one — this uses setInterval() to accomplish the same effect:
let i = 1; setInterval(function run() { console.log(i); i++; }, 100);
recursive /receive
How do recursive setTimeout() and setInterval() differ? 递归的setTimeout和setInterval的区别?
The difference between the two versions of the above code is a subtle one.
第一个是两次运行至少间隔100ms
setInterval()是运行是40ms,那么间隔60ms后就会再次运行。
如果你的程序运行时间超过100ms,那最好还是用递归的setTimeout来执行。至少保证间隔时间,可以不管运行时间,这样不会犯错误。
第一个是两次运行至少间隔100ms
setInterval()是运行是40ms,那么间隔60ms后就会再次运行。
如果你的程序运行时间超过100ms,那最好还是用递归的setTimeout来执行。至少保证间隔时间,可以不管运行时间,这样不会犯错误。
- Recursive setTimeout() guarantees the given delay between the code execution completion and the next call. The delay for the next execution will start counting only after the code has finished running, therefore excluding the time taken to run the code. In this example, the 100 milliseconds will be the delay between the run code finishing, and the next run call.
- The example using setInterval() does things somewhat differently. The interval you chose includes the time taken to execute the code you want to run in. Let's say that the code takes 40 milliseconds to run — the interval then ends up being only 60 milliseconds.
- When using setTimeout() recursively, each iteration can calculate a different delay before running the next iteration. In other words, the value of the second parameter can specify a different time in milliseconds to wait before running the code again.
When your code has the potential to take longer to run than the time interval you’ve assigned, it’s better to use recursive setTimeout() — this will keep the time interval constant between executions regardless of how long the code takes to execute, and you won't get errors.
阅读量: 640
发布于:
修改于:
发布于:
修改于: