JavaScript setTimeout()

Back to home
Logicmojo - Updated Aug 28, 2021



Javascript SetTimeout()

Javascript code is often run in a synchronous manner. However, there may be times when you need to invoke a function later rather than right now, for which we have setTimeout.

The setTimeout() method allows you to run code after a specified length of time has passed. The method can be thought of as a means to set a timer to run JavaScript code at a specific interval.

The following code, for example, will print "Hello World" to the JavaScript console after 2 seconds:

setTimeout(function(){
    console.log("Hello World");
}, 2000);

console.log("setTimeout() example...");



Once two seconds have passed since the code was executed by JavaScript, the code will print "setTimeout() example..." to the console, followed by "Hello World."

Syntax: setTimeout(function, time)

Parameters:
⮞ function: It is the reference to a function that is going to run after a given time.
⮞ time: The milliseconds after which the given function will execute.

How to Cancel the setTimeout Method

The clearTimeout() method can also be used to prevent the setTimeout() method from performing the function.

The id supplied by setTimeout() is required by clearTimeout() to determine which setTimeout() function to cancel.

const timeoutId = setTimeout(function(){
    console.log("Hello World");
}, 2000);

clearTimeout(timeoutId);
console.log(`Timeout ID ${timeoutId} has been cleared`);



JavaScript clearTimeout()

Syntax: clearTimeout(intervalID);

Here, the intervalID is the return value of the setTimeout() method.

// program to stop the setTimeout() method

let count = 0;

// function creation
function increaseCount(){

    // increasing the count by 1
    count += 1;
    console.log(count)
}

let id = setTimeout(increaseCount, 3000);

// clearTimeout
clearTimeout(id); 
console.log('setTimeout is stopped.');



Recursive setTimeOut Calls

A recursive setTimeout timer can be more useful than a setInterval timer in some cases. For example, if the actions run as part of the timer take a long period, using setInterval can result in no delay between them because the delay is calculated from the task's start. We have complete control over when the delay begins if we use a recurring setTimeout timer instead. A recursive setTimeout call looks like this:

let i = 0;  
function increment() {
   i++;   
   console.log(i); 
}  
let timer = setTimeout(function myTimer() {  
   increment();    
   timer = setTimeout(myTimer, 1000); 
}, 1000);
setTimeout(() => {   
console.log('Cancelling');  
 clearTimeout(timer); }, 7000);



Conclusion: At this point, you should have a better understanding of JavaScript setTimeout(). As you work on JavaScript programming projects, each of these will become more important.