Monday, April 30, 2018

setTimeout with clearTimeout

We can use “timer identifier” which will be returned by setTimeout and the same we can use to cancel the execution.

Syntax:



let timerId = setTimeout(...);
clearTimeout(timerId);

Example:



1
2
3
let myVar = setTimeout(function(){ alert("Hello"); }, 3000);

let xxx = clearTimeout(myVar);

Explanation:

1. Line number 1 will be executed initially

2. To display the alert Hello message 3 seconds need to be waited.

3. But line number 3 will be executed before three seconds. So alert message will not be displayed here.

No comments:

Post a Comment