window 中的定时器
1、定时器分类
1、周期性定时器【广告】
每间隔一定的时间后,就执行一遍指定程序,反复执行
2、一次性定时器
在指定的时间间隔之后,只执行一次操作
2、周期性定时器
1、声明定时器
var ret = setInterval(fun,time);
fun:要周期性执行的操作,可以是匿名函数
time:时间间隔周期,以毫秒为单位
ret:返回已创建好的定时器对象
2、清除定时器
clearInterval(timer)
timer:创建好的,要停止的定时器对象
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var timer ; //全局的定时器对象
function testInterval(){
timer = setInterval(function(){
var now = new Date();
console.log(now.toLocaleString());
},1000);
}
function stopInterval(){
clearInterval(timer);
}
</script>
<button onclick="testInterval()">开始</button>
<button onclick="stopInterval()">停止</button>
</body>
</html>
3、一次性定时器
1、声明一次性定时器
var ret = setTimeout(fun,time);
fun:指定时间间隔后要执行的操作
time:时间间隔
ret:返回已启动的定时器对象
2、清除定时器
clearTimeout(timer);
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var timer = null ; //全局定时器变量
function closeWindow(){
if(confirm("确认关闭网页吗?")){
timer = setTimeout(function(){
window.close();
},5000);
}
}
function cancelClose(){
if(timer != null){
clearTimeout(timer);
alert("取消成功!");
}
}
</script>
<button onclick="closeWindow()">关闭网页</button>
<button onclick="cancelClose()">取消关闭</button>
</body>
</html>