先决条件: setTimeout()和setInterval()
null
clearTimeout() javascript中的clearTimeout()函数用于清除由 setTimeout() 在那之前的功能。
- setTimeout() 函数有两个参数。第一个是要执行的函数,第二个是要执行多少时间(毫秒)。
- setTimeout() 在给定时间后执行传递的函数。返回的数字id值 setTimeout() 函数存储在变量中,并将其传递到 clearTimeout() 函数来清除计时器。
例子:
<!DOCTYPE html> < html > < head > < title > HTML | DOM Windows clearTimeout() method </ title > </ head > < 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 > |
说明: GeekSforgeks按钮的颜色在3秒钟后仅改变一次。点击GeekSforgeks按钮3秒前点击Stop以清除超时。
clearInterval() javascript中的clearInterval()函数用于清除由 setInterval() 在那之前的功能。
- setInterval() 函数有两个参数。第一个是要执行的函数,第二个是要执行多少时间(毫秒)。
- setInterval() 在给定的时间间隔内执行传递的函数。返回的数字id值 setInterval() 函数存储在变量中,并将其传递到 clearInterval() 函数来清除间隔。
例子:
<!DOCTYPE html> < html > < head > < title > HTML | DOM Windows clearInterval() method </ title > </ head > < 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 > |
说明: 在本例中,GeekSforgeks的颜色每3秒就会改变一次,然后再次改变。单击“停止”以清除间隔。
支持的浏览器: 支持的浏览器 clearTimeout()和clearInterval()方法 以下列出了:
- 谷歌Chrome1.0
- Internet Explorer 4.0
- 火狐1.0
- 歌剧4.0
- Safari 1.0
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END