understanding execution of setTimeout() functions

2019-07-12 19:47发布

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.

2条回答
Juvenile、少年°
2楼-- · 2019-07-12 20:32

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

查看更多
Luminary・发光体
3楼-- · 2019-07-12 20:40

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.

查看更多
登录 后发表回答