在编写代码时经常需要设置延时操作,现在探究一下关于单次定时和多次定时的代码
<!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。