Prerequisite: setTimeout() and setInterval()
clearTimeout()
The clearTimeout() function in javascript clears the timeout which has been set by setTimeout()function before that.
- setTimeout() function takes two parameters. First a function to be executed and second after how much time (in ms).
- setTimeout() executes the passed function after given time. The number id value returned by setTimeout() function is stored in a variable and it’s passed into the clearTimeout() function to clear the timer.
<!DOCTYPE html> < html > < body > < button id = "btn" onclick = "fun()" style = "color: blue;" > GeeksForGeeks</ button > < button id = "btn" onclick = "stop()" >Stop</ button > < script > var t; function color() { if(document.getElementById('btn').style.color=='blue') {document.getElementById('btn').style.color='green'; } else {document.getElementById('btn').style.color='blue';} } function fun() { t =setTimeout(color, 3000); } function stop() { clearTimeout(t); } </ script > </ body > </ html > |
Explanation:
The GeeksForGeeks button color changes after 3 seconds for just one time. Click on Stop before 3 seconds after clicking GeeksForGeeks button to clear Timeout.
clearInterval()
The clearInterval() function in javascript clears the interval which has been set by setInterval() function before that.
- setInterval() function takes two parameters. First a function to be executed and second after how much time (in ms).
- setInterval() executes the passed function for the given time interval. The number id value returned by setInterval() function is stored in a variable and it’s passed into the clearInterval() function to clear the interval.
<!DOCTYPE html> < html > < body > < button id = "btn" onclick = "fun()" style = "color: blue;" > GeeksForGeeks</ button > < button id = "btn" onclick = "stop()" >Stop</ button > < script > var t; function color() { if(document.getElementById('btn').style.color=='blue') {document.getElementById('btn').style.color='green'; } else {document.getElementById('btn').style.color='blue';} } function fun() { t =setInterval(color, 3000); } function stop() { clearInterval(t); } </ script > </ body > </ html > |
Explanation:
In this example, the GeeksForGeeks color changes and stays same for every 3 seconds, after that it changes again. Click on Stop to clear the interval.
This article is attributed to GeeksforGeeks.org
0
0
leave a comment
0 Comments