您的位置:首页 > Web前端 > JavaScript

JavaScript设置定时器和清除

2019-05-22 19:30 281 查看
在编写代码时经常需要设置延时操作,现在探究一下关于单次定时和多次定时的代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="text/javascript">
window.onload = function () {
var stime = null;
var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');
one.onclick = function(){
setTimeout(function () {
alert('hello')},3000)
};//单次

two.onclick = function(){
function ft() { alert('你好')}
stime = setInterval(ft,4000)
};//多次

three.onclick = function () {
clearInterval(stime);
stime = null
}//清除定时器
}
</script>
</head>
<body>
<button id="one">单次</button>
<button id="two">多次</button>
<button id="three">清除</button>
</body>
</html>

单次定时使用 setTimeout后面执行匿名函数3000毫秒后弹出“hello”,只执行一次。
多次定时使用 stime = setInterva,多次执行。
为了节约系统资源,多次定时通常需要清除操作,使用clearInterval。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: