JavaScript setTimeout() Function: Complete Guide

JavaScript setTimeout() is a built-in function that calls a function after several milliseconds. The setTimeout() function waits for the given time and executes the function again and again. This article is all about learning the JavaScript setTimeout() function. The setTimeout() function works almost like the setInterval() function.

Syntax

setTimeout(func, delay in millisecond);

Parameters

This function accepts two parameters.

function: the first parameter is a function to be executed.

delay: This is the number of milliseconds before the next function execution.

The setTimeout()  is executed only once.

Use setInterval() method if you need repeated execusions.

soccerTimeout = setTimeout(func, milliseconds);

Return Value

It returns the id of the timer. This id can be passed to clearTimeout() to cancel the timer.

Example

const soccerTimeout = setTimeout(soccerGretting, 3000);

function soccerGretting() 
{
   console.log("Happy Birthday Ronaldo!");
}

Output

You can see the output in the terminal after 3000ms or 3 sec “Happy Birthday Ronaldo!”.

JavaScript clearTimeout()

JavaScript clearTimeout() is a built-in function that clears a timer set with the setTimeout() method. If the parameter provided does not identify a previously established action, this method does nothing.

To clear a timeout in JavaScript, use the clearTimeout() function and pass id, returned from the setTimeout() function.

Syntax

clearTimeout(timeoutID)

Arguments

The timeoutID is an identifier of the timeout you want to cancel. This ID was returned by the corresponding call to setTimeout().

Return value

It returns a null or no value.

Use clearTimeout(soccerTimeout) to prevent soccerGretting from running:

Example

const soccerTimeout = setTimeout(soccerGretting, 3000);
clearTimeout(soccerTimeout);

function soccerGretting() 
{ 
 console.log("Happy Birthday Ronaldo!");
}

Output

You can see that soccerGretting() function is not called because we have used clearTimeout() function

You can see that after using the clearTimeout() function, the setTimeout() function is not called, and therefore, it won’t execute.

Conclusion

We learned about setTimeout() and clearTimeout() in JavaScipt. The working of setTimeout() function is almost the same as the setInterval() function.

Related posts

How to Get Time in 12 Hour Format in Javascript

How to Convert Timestamp to Date in JavaScript

How to Convert Date to Timestamp in JavaScript

Leave a Comment