DEV Community

Mrityunjay-Palled
Mrityunjay-Palled

Posted on

setTimeout(),setInterval() and clearTimeout() in JavaScript

setTimeout(): This method allows us to execute a piece of code after a certain amount of time.

Image description

In the above example, the myName function will be executed after 2 seconds (2000 milliseconds). For the setTimeout() function, the duration after which the code has to execute will be passed in milliseconds.

Image description

In the above example, we can see that we are passing a parameter to the myName function via the setTimeout() function.

setInterval(): This method executes a piece of code repeatedly with the fixed time delay between each call

Image description

In the above example, the myName function will be executed repeatedly after every 2 seconds (2000 milliseconds).We can also pass parameters to the setInterval() method, similar to the setTimeout() method as discussed before.

clearTimeout(): This method helps us to clear the timeout previously set by the setTimeout() method. The setTimeout() method returns an ID which must be passed to the corresponding clearTimeout() method

Image description

In the above example, the ID returned by the setTimeout() method is stored in the timeoutID and will be passed to the clearTimeout() method. In the above scenario, we have two buttons: one to show the alert and the other one to stop the alert. 
We have a function named showAlert() that will display the alert message. The clearTimeout() function is used by stopAlert() to clear all timeout settings. The alert window will not be displayed if the stopAlert button is clicked before the completion of 2 seconds from when you clicked the showAlert button.

Top comments (0)