How to Delay execution with setTimeout in JavaScript

How to Delay execution with setTimeout in JavaScript

Do you want to delay the execution of the code? Then, the JavaScript method setTimeout could be handy.

In this tutorial, you will learn the setTimeout syntax in detail and the tips on using it most effectively. You will also learn about the method of clearing the timeout.

By the end of this tutorial, you should be able to handle setTimeout like a pro!


How setTimeout works

Most of us use setTimeout all the time without realizing it.

It's a handy function that helps us control the code execution after a set delay.

The code will run once after the specified delay has passed when using it.

You can specify a delay in milliseconds, which allows you to precisely control how long the code will wait before executing the code inside.

For example, you can use it to queue up multiple tasks and run them all at once after the delay has elapsed.

Passing Parameters to setTimeout

It takes two parameters: the function name and the delay value in milliseconds.

You can also pass the direct callback or an arrow function as the first parameter.

setTimeout example

Let's take a look at an example of how to use it.

Quick Example

Redirect a user to a different page after 5 seconds.

You can redirect a user in JavaScript through window.location.href = "URL"

 setTimeout example

clearTimeout – Clear the execution of setTimeout

Clearing the timeout period is useful for a variety of purposes in code.

It can be used for cleaning up code or canceling an action that was already started.

For example, if you set a timer for 10 minutes and want to cancel it early or cancel the timeout based on a specific condition. You can use clearTimeout.

This will stop the timer from executing and return the timer to its initial state.

You can also use clearTimeout to avoid infinite loops and other problems.

clearTimeout example



Is there any difference between setTimeout and setInterval?

setTimeout executes the code after a set amount of time, and it only runs once. In contrast, setInterval executes the code multiple times according to the interval set in milliseconds.

Can I create a countdown timer with setTimeout in javascript?

You can not create a countdown timer because it runs only once. However, you can use the setInterval method for this purpose.

What is the return value of setTimeout?

It returns timeoutID, which is a positive integer value. To stop the timeout, this value may be passed to clearTimeout.


Our Coding guides: 


In this article, you have learned all about setTimeout. You have learned how it works, how to cancel it, and how to pass its parameters.

Next, learn to build your own Words and Characters counting application in JavaScript.

Leave a comment

All comments are moderated before being published.

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.