JavaScript setTimeout() Function

If you want to know about the setTimeout() function in javascript and how to use it, this blog will surely help you understand the setTimeout() function with coding examples.

1. setTimeout() function

The setTimeout() function executes a block of code only once after the specified time.

Let’s have one instance of setTimeout() method:

function display() {

    console.log('I am the second one');
}

setTimeout(display, 4000);

console.log('I am the first one');

Output:

"I am the first one"
"I am the second one"

So, In the above example, the setTimeout() calls display() method after 4000 milliseconds, i.e. 4 sec. That’s why “I am the second one” is displayed after  4 sec of delay.

Syntax:  setTimeout(function, milliseconds, parameter, parameter2….);

  1. Function: In the first parameter, we pass the function containing the block of code that we want to execute.
  2. Milliseconds: In the second parameter, we pass the time after which the code will execute. And we need to pass the time in milliseconds (1 second = 1000 milliseconds). If we miss passing the second parameter, the setTimeout() will immediately execute without waiting.
  3. Parameter1, Parameter2…: In the setTimeout(), we can also pass additional parameters that we can use inside the function.
function display(name, rollno) {
  
    console.log('My name is '+ name);
  
    console.log('My roll no is '+ rollno);
}

setTimeout(display, 4000, "JavaScript", "22");

For instance, You may wonder why not directly pass the values inside the display function rather than passing inside the setTimeout() method like this:

function display(name, rollno) {
  
    console.log('My name is '+ name);
  
    console.log('My roll no is '+ rollno);
}

setTimeout(display("JavaScript", "22"), 4000);

If we do so, the JavaScript will execute the function directly without waiting as in the parameter, we are passing the function call, not a function parameter. So this is why if you need to pass parameters to the function, pass them inside the setTimeout().

2. Using setTimeout() function recursively

To understand this, let’s have one example:

function displayTime() {

    // returns new date and time
    let dateTime= new Date();

    // returns the current local time
    let time = dateTime.toLocaleTimeString();

    console.log(time)

    let id = setTimeout(displayTime, 4000);

}

displayTime();// calling the function

In the above example, the displayTime() function displays the local time after every 4 sec. However, the setTimeout() executes a block of code only once, but here the displayTime() is calling itself recursively and displaying time after every 4 seconds.

3. clearTimeout() function

In the above setTimeout() recursively calling example, the program executed after every 4 seconds and didn’t stop. Now you may wonder how we can stop it? If you want to stop this program, you can use the clearTimeout() function.

The clearTimeout() method cancels the setTimeou() method before its execution.

Syntax:  clearTimeout(id);

This method requires an id that is returned by setTImeout() to know which method it needs to cancel.

Let’s take one example to understand this:

function displayTime() {

    //returns new date and time
    let dateTime= new Date();

    // returns the current local time
    let time = dateTime.toLocaleTimeString();

    console.log(time)

}

     
     let id = setTimeout(displayTime, 4000);

     clearTimeout(id);

     console.log('stop!')
     

Output:

"stop!"

So, in the above example, the clearTimeout() function stops the program and prints “Stop!”

However, in the case of multiple setTimeout(), save the multiple ids in a separate variable and then use the clearTimeout()on every id to clear them all.

4. Conclusion

Hopefully, you got a complete overview of the JavaScript setTimeout() and JavaScript clearTimeout() and how to use them. So now it’s your turn to write us about any questions or suggestions you have in the comment section below.

Also, to get a better understanding of JavaScript Asynchronous, you can read our next blog JavaScript Callback function.

Some links on this page are affiliate links. This means that if you choose to make a purchase, we may earn a small commission at no extra cost to you. For more information, Go here

Leave a Reply

Your email address will not be published. Required fields are marked *