How to catch exceptions in setTimeout and setInterval

In JavaScript, we use the try...catch statement to capture unexpected errors and exceptions.

How does try...catch work?

try {
    // block of code
} catch (error) {
    // handle the error
} finally {
    // execute in all cases
}
  1. The try clause is executed first.
  2. If no exception is thrown, the catch clause is ignored, and the execution of the try statement is completed.
  3. If an exception is thrown during the execution of the try clause, the rest of this clause is ignored. The catch clause is executed, and what comes after the try statement is executed.
  4. The finally clause is optional and executes after both clauses, regardless of whether an exception is thrown or not.

Capturing exceptions in setTimeout and setInterval

Both setTimeout and setInterval functions call or evaluate an expression after a specified number of milliseconds. If we put these methods inside the try clause and an exception is thrown, the catch clause will not catch any of them:

try {
  setTimeout(() => {
    throw new Error(`An exception is thrown`)
  }, 500)
} catch (error) {
  console.error({ error })
}

Uncaught Exception Example

This is because the try...catch statement works synchronously, and the function in question is executed asynchronously after a certain period of time.

To resolve this issue, we have to put the try...catch block inside the function:

setTimeout(() => {
  try {
    throw new Error(`An exception is thrown`)
  } catch (error) {
    console.error({ error })
  }
}, 500)

Caught Exception Example

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.