Are equal timeouts executed in order in Javascript?

前端 未结 5 1875
小鲜肉
小鲜肉 2020-12-01 10:49

Suppose I do

setTimeout(foo, 0);

...

setTimeout(bar, 0);

Can I be sure foo will begin executing before bar? What if instead of 0 I use a

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 11:10

    The answer is: No, execution order is not guaranteed. I have occasionally seen non-FIFO ordering in chrome 40, especially if I pause in debugger while timeouts are pending. I also had a rare sighting in the wild - it was the only plausible explanation of an incident I investigated.

    If you need guaranteed execution order, instead of setTimeout(callback, 0) you can do this:

    var queue = [];
    function handleQueue() {
        queue.shift()();
    }
    function queueCallback(callback) {
       queue.push(callback);
       setTimeout(handleQueue, 0);
    }
    

    Now, for guaranteed foo, bar order you can:

    queueCallback(foo);
    ...
    queueCallback(bar);
    

提交回复
热议问题