1
00:00:00,000 --> 00:00:03,270
Why does my browser run a timer

2
00:00:03,270 --> 00:00:06,960
last when I asked for zero milliseconds?

3
00:00:07,140 --> 00:00:10,760
Zero does not interrupt the code running now.

4
00:00:10,760 --> 00:00:13,840
The timer callback must wait for a later task.

5
00:00:13,840 --> 00:00:16,700
A task is one turn of work in the browser.

6
00:00:16,880 --> 00:00:20,600
The call stack tracks function calls running now.

7
00:00:20,600 --> 00:00:22,800
This script logs A, sets up the

8
00:00:22,800 --> 00:00:26,320
timer and promise callback, then logs B.

9
00:00:26,320 --> 00:00:28,000
Neither callback interrupts it.

10
00:00:28,180 --> 00:00:32,120
Then why does the promise callback get there first?

11
00:00:32,120 --> 00:00:34,380
I added the timer before it.

12
00:00:34,560 --> 00:00:37,225
A ready promise callback is a

13
00:00:37,225 --> 00:00:40,040
microtask: work checked after the current task.

14
00:00:40,040 --> 00:00:43,880
The browser drains that queue before starting another task.

15
00:00:43,880 --> 00:00:47,920
So we get A, B, promise, timer.

16
00:00:48,100 --> 00:00:50,400
If a timer must follow an async

17
00:00:50,400 --> 00:00:53,720
step, schedule it after awaiting that step.

18
00:00:53,720 --> 00:00:55,460
Do not use timer delays to

19
00:00:55,460 --> 00:00:57,860
guess when other work will finish.

20
00:00:58,040 --> 00:01:01,510
A network response may arrive later, so this

21
00:01:01,510 --> 00:01:04,440
order is not a rule for every promise.

22
00:01:04,440 --> 00:01:07,560
Timers can also run late when the browser is busy.

23
00:01:07,740 --> 00:01:11,040
Zero milliseconds.

24
00:01:11,040 --> 00:01:13,860
So the timer makes promises like my internet company.
