标签:
定时器的使用场合
setInterval() 方法,按照指定的周期(以毫秒记)来调用函数或计算表达式
setInterval() 方法会不停的调用函数,知道 clearInterval() 被调用或窗口被关闭,由setInterval() 返回的ID值可作用于 clearInterval() 方法的参数
setInterval(code,millisec) code 要调用的函数或执行的代码,millisec 周期调用或调用code之间的时间间隔(以毫秒记)
返回值: 一个可以传递给 window.clearInterval() ,从而取消对code的周期性执行的值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test测试例子</title>
<script type="text/javascript">
// setInterval() 测试例子
var i = 0;
var int = setInterval(function(){
console.log(i++);
}, 1000)
function stop(){
clearInterval(int);
console.log("ok");
}
</script>
</head>
<body>
<input type="button" value="停止" onclick="stop();">
</body>
</html>
setTimeout() 方法,在指定的毫秒数后调用函数或计算表达式
setTimeout(code,millisec) code 要执行的函数活执行的代码,millisec 在执行代码前需等待的毫秒数
注意:setTimeout() 只执行code一次,如果要多次调用,请使用 setInterval() 或者让code 自身再次调用 setTimeout()
clearTimeout(id_of_setTimeout) 取消setTimeout() 设置的timeout, id_of_setTimeout 是 setTimeout() 返回的id
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test测试例子</title>
<script type="text/javascript">
// setTimeout() 测试例子
var i = 0;
var t;
function time5(){
t = setTimeout(function(){
console.log(i++);
time5();
},1000);
}
function stop(){
clearTimeout(t);
console.log("okl");
}
time5();
</script>
</head>
<body>
<input type="button" value="清除定时器" onclick="stop();">
</body>
</html>
标签:
原文地址:http://www.cnblogs.com/geek12/p/4527393.html