Timer Functions in JavaScript

JavaScript·2 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).

Unlock the program 🚀

Pay once, own it forever.

€79

30-day money-back guarantee

  • 13 modules
  • 113 lessons with full-code examples
  • 29 projects with commented solutions
  • All future lesson and project updates
  • Lifetime access

By submitting this form, you agree to the Terms & Conditions and Privacy Policy.