CodeBlanks Logo Icon CodeBlanks

Asynchronous callbacks

JavaScript course · Intermediate · Lesson 67/134

Learn how a callback is later invoked by the event loop.

Asynchronous callbacks

Some callbacks do not run right away; they are called later. setTimeout is the most common example: the callback you provide is placed into the event loop after the delay you set.

console.log('One');
setTimeout(() => {
  console.log('Two');
}, 0);
console.log('Three');

The output order is 'One, Three, Two'. The setTimeout callback waits until the call stack is empty. This pattern is called an asynchronous callback.

The call stack and the callback queue

JavaScript is single-threaded; it does one thing at a time. The call stack holds the functions currently running. Calls like setTimeout start a timer in the browser; when the timer elapses, the callback is placed into the callback queue.

The event loop constantly checks two things: is the call stack empty, and is there a waiting callback in the queue? Once the stack is empty, it takes the next callback from the queue and runs it. That is why asynchronous callbacks always wait for the current code to finish.

Exercise Write the runLater function

Define a function named runLater. It should take two parameters: delay (in milliseconds) and callback. Inside the function, use setTimeout to call callback after delay ms.

Show example solution
function runLater(delay, callback) {
  setTimeout(callback, delay);
}

Test yourself

  1. What is the output of the following code?

    console.log('A');
    setTimeout(() => console.log('B'), 0);
    console.log('C');
    • A, C, B
    • A, B, C
    • B, A, C
    • C, A, B
    Show answer

    A, C, B — Correct! Synchronous code finishes first; the setTimeout callback runs last.

  2. Complete the setTimeout callback

    setTimeout(() => {
      console.log(____);
    }, 500);
    Show answer
    setTimeout(() => {
      console.log('Ready');
    }, 500);
  3. Match the concepts

    call stack
    Currently running
    callback queue
    Waiting callbacks
    event loop
    Watches the stack
    setTimeout
    Schedules callback
  4. Which always runs first?

    • setTimeout callback
    • Event loop
    • Synchronous code
    • Callback queue
    Show answer

    Synchronous code — Correct! Synchronous code runs immediately on the call stack; asynchronous callbacks wait for it.

All lessons in Intermediate