Are equal timeouts executed in order in Javascript?

前端 未结 5 1870
小鲜肉
小鲜肉 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:14

    I read through the Firefox source code, and at least for that browser, there is a sequentiality guarantee for timeouts which are specified in nondecreasing order. Otherwise all bets are off.

    Specifically, if in a given execution context you set a timeout for n, and then one for m, where n <= m, the targets will be executed in the order the timeouts were set.

    But don't take my word for it. I believe the window implementation is in nsGlobalWindow.cpp, and the method which actually decides where timeouts go in the execution queue is called InsertTimeoutIntoList. It looks like the method traverses the queue backwards looking for the first timeout which is less than or equal to the given timeout, and inserts the given timeout after it.

    Of course when the timeout is set the current clock time is added to the timeout value. This is why the timeout values must be in nondecreasing order for the targets to be executed in sequence.

提交回复
热议问题