1、概念
-
- 一、js中能够经过setTimeout函数设置定时器,让指定的代码在指定的时间运动. 若是咱们但愿在setTimeout之行前终止其运行就能够使用clearTimeout()。
-
- 二、clearTimeout()用于重置js定时器,若是你但愿阻止setTimeout的运行,就能够使用clearTimeout方法。
-
2、使用场景
-
- 一、写计时器
-
- 二、须要让程序隔一段时间处理什么事情,如3秒后自动关闭弹出框等
-
- 三、事件延迟,知足业务需求,如鼠标从主菜单moveout的时候,判断鼠标是否moveover副菜单,再隐藏副菜单。
-
3、使用方法
<html>
<head>
<script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
function stopCount()
{
clearTimeout(t)
}
</script>
</head>
<body>
<form>
<input type="button" value="开始计时!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="中止计时!" onClick="stopCount()">
</form>
<p>
请点击上面的“开始计时”按钮。输入框会从 0 开始一直进行计时。点击“中止计时”可中止计时。
</p>
</body>
</html>