Adding delays with setTimeout - JavaScript

Adding delays with setTimeout - JavaScript

In this blog, we will be learning about setTimeout method and how it can be used to add delays in the execution of a certain code.

The setTimeout method allows you to execute a piece of code after a certain amount of delay.

Let's say, you want to show a message to the user of your website after he has spent 5 seconds on your website.

This can be implemented with the use of setTimeout method. Let's see how.

The syntax of setTimeout method looks like this:

setTimeout( functionToExecute , delay)

Yes, it's that simple. In the syntax :

  • functionToExecute denotes reference to the function that must be called after the given time expires.
  • delay denotes the time until javascript has to wait to execute the function. The delay is given in milliseconds.

Therefore, to show a message after 5 seconds, we need to set the delay of 5000 milliseconds.

So let's implement it.

function showMessage(){
  //code to showMessage to the user
}

setTimeout( showMessage, 5000 )

And... that's it. We now have a timer of 5 seconds and a function that will show the message to the user when the timer expires.

Passing arguments to the callback function

In case you want to show a custom message to the user then you will have to send the message as an argument to the showMessage function. Normally, we would pass arguments to a function while making a function call. If we try doing that here then we would end up executing the function without waiting for the timer.

setTimeout( showMessage("Hello") , 5000) //executes instantly

So, what's the solution? The setTimeout function provides a solution to this problem. You can pass the arguments that must be ultimately passed to the function which will be executed later to the setTimeout method.

setTimeout( showMessage, 5000, "Hello" )

All the arguments given to setTimeout after the first two arguments (i.e the callback function and delay) will be passed to the callback function which is executed after the timer expires.

How do you cancel a setTimeout?

The setTimeout method returns an id. This id can be used to clear the Timeout using the clearTimeout method

let id = setTimeout( showMessage, 5000 )
clearTimeout(id)

Thank you for reading this blog, please leave your feedback comments