Timer Functions in JavaScript

4 min readยทJan 1, 2025

In JavaScript, the setTimeout() and setInterval() functions are respectively used to delay the execution of a callback function, thus creating asynchronous execution.

๐Ÿ“š As a reminder, a callback function is a function passed as argument to another function โ€” usually asynchronous โ€” that is executed upon completion of the main function to process its result or handle errors.

Delay the execution of a callback

The setTimeout() function is used to execute a callback function once a certain amount of milliseconds have elapsed.

let timeoutID = setTimeout(callback, delay)

Where:

  • callback is a function.
  • delay is the amount of milliseconds to wait before executing the callback.

This function returns an identifier that can be passed as argument to the clearTimeout() function to cancel the timeout.

๐Ÿ’ก In backend development, this function is generally used to:

  • Retry failed tasks with backoff (e.g, in 1s, then 3s, and so on).
  • Timeout tasks that exceed a maximum duration (e.g, mark as failed after 30s).
  • Shutdown processes gracefully (e.g, stop processing new tasks and initiate cleanup).
  • Schedule cleanup tasks (e.g, delete temporary files and in-memory cache entries).

Example

Let's consider this script:

console.log('Start');

setTimeout(() => {
  console.log('Callback');
}, 2000);

console.log('End');

When executed, it will:

  1. Execute the 1st synchronous console.log() function.
  2. Execute the setTimeout() function and start a 2000ms timer.
  3. Execute the 3rd synchronous console.log() function.
  4. Add the callback to the timers queue once the 2000ms have elapsed, then wait for Node.js to reach the Timers phase and execute it if the main thread is free.

Which will produce this output:

Start
End
Callback

Note: Since the callback is added to the Timers queue only after the timer expires, this means that the event loop doesn't guarantee the exact execution time of the callback.

Delay the interval of a callback

The setInterval() function is used to execute a callback function multiple times, with a fixed delay between each call:

let intervalID = setInterval(callback, interval)

Where:

  • callback is a function.
  • delay is the amount of milliseconds to wait between each execution of the callback.

This function returns an identifier that can be passed as argument to the clearInterval() function to cancel the interval.

๐Ÿ’ก In backend development, this function is generally used to:

  • Run periodical tasks (e.g., refresh the in-memory cache every minute).
  • Perform periodical health checks (e.g., check if a database is still up and running).
  • Aggregate metrics and logs (e.g., flush log files into a database).

Enjoying the courses?

I've made these courses completely free so anyone can learn from them. If they've helped you and you'd like to actively support the work behind BackendBrewery, you can leave a tip:

Support BackendBrewery
Timer Functions in JavaScript | Backend Brewery