understanding execution of setTimeout() functions that follow one another

家住魔仙堡 提交于 2019-12-12 17:50:57

问题


I need to execute multiple functions one after another in fixed time intervals, thus using setTimeout. I want to ensure that I understand how it executes. I have following logic:

setTimeout(function() {
  //Execute first function
}, 200);

setTimeout(function() {
  //Execute second function
}, 400);

setTimeout(function() {
  //Execute third function
}, 600);

Does this mean that first function executes after 200ms, second one 200ms after the first, and the third one 200ms after the second and so on? Or do I need to change something.


回答1:


Does this mean that first function execute after 200ms, second one 200ms after first and third one 200ms after second and so on?

Essentially, yes that's what it means. Bear in mind however that the specification only guarantees that the delay parameter is a minimum time that must be awaited, and browsers can and do throttle these calls sometimes - notably if the tab is not active:

Note: This API does not guarantee that timers will fire exactly on schedule. Delays due to CPU load, other tasks, etc, are to be expected.

and:

  1. Optionally, wait a further user-agent defined length of time.

Note: This is intended to allow user agents to pad timeouts as needed to optimise the power usage of the device. For example, some processors have a low-power mode where the granularity of timers is reduced; on such platforms, user agents can slow timers down to fit this schedule instead of requiring the processor to use the more accurate mode with its associated higher power usage.

Also, if any of your functions take a noticeable amount of time to run, the delay between the end of one function finishing and the next starting may not be 200ms - it could be less.




回答2:


Following James' answer, in order to guarantee this minimum delay, you should trigger the next setTimeout() inside the anonymous callback, each of them with the 200ms delay specified:

setTimeout(function() {
    //Execute first function

    setTimeout(function() {
        //Execute second function

        setTimeout(function() {
            //Execute third function
        }, 200);

    }, 200);

}, 200);

This way you can be sure that the delay between each function will be at least 200ms



来源:https://stackoverflow.com/questions/32653973/understanding-execution-of-settimeout-functions-that-follow-one-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!