CodeBlanks Logo Icon CodeBlanks

Timers queue

Learn the timers queue and setTimeout ordering.

Timers queue

The timers queue holds callbacks registered with setTimeout and setInterval. In the timers phase the event loop runs the timers whose deadline has passed. Timers are ordered by delay; smaller delays run first.

A timersByDelay(delays) function models this ordering: the input [100, 10, 50] returns '10,50,100'. delays.slice().sort((a, b) => a - b) first copies the array (to avoid mutating the original), then sorts numerically. .join(',') turns it into a string. This shows that the timers phase runs callbacks in delay order. The output is 10,50,100; the smallest delay first.

Numeric sorting

JavaScript sort defaults to string sorting; it orders numbers incorrectly ([10, 100, 50] becomes [10, 100, 50]). For numeric sorting you pass a comparator: (a, b) => a - b. This sorts ascending.

Example: [100, 10, 50].sort((a, b) => a - b) gives [10, 50, 100]. We take a copy with delays.slice() because sort mutates in place. .join(',') yields the string '10,50,100'. This models the timers phase running callbacks in correct delay order. There is no timer uncertainty; the ordering is deterministic. The output is 10,50,100.

Practice Write the timers ordering

Write function timersByDelay(delays). Return delays.slice().sort((a, b) => a - b).join(','). Print console.log(timersByDelay([100, 10, 50])).

Starter code

index.js
// Write a timersByDelay function
// Sort delays from small to large
// Join with a comma and print
// Call with [100, 10, 50]
// write here

Sample solution

index.js
function timersByDelay(delays) {
  return delays.slice().sort((a, b) => a - b).join(',');
}
console.log(timersByDelay([100, 10, 50]));

Expected output

10,50,100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the sort call

Question
return delays.slice().____((a, b) => a - b).join(',');
Answer
return delays.slice().sort((a, b) => a - b).join(',');

Explanation: sort orders the array.

2 What does [100, 10, 50].sort((a, b) => a - b) give?

index.js
[100, 10, 50].sort((a, b) => a - b)
  • [100, 50, 10]
  • [10, 100, 50]
  • [10, 50, 100] Correct answer
  • [50, 10, 100]

Explanation: a - b sorts ascending: [10, 50, 100].

3 Match each concept to its description

Term Meaning
setTimeout One-shot timer
sort Orders an array
slice Takes a copy of an array
timers phase Runs timers

All lessons in Expert