JavaScript基础学习 定时器setTimeout与setInterval
定时器setTimeout
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=devcie-width,initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div>
</div>
<button>点击停止two-爆炸</button>
<script>
// window.setTimeout(回调函数,延时的时间) 单位:毫秒 如果不加默认为0
// window可以省略
// 当延时时间过去时,才会执行我们这个回调函数
// 1 第一种写法
window.setTimeout(function() {
console.log('one-爆炸了');
}, 3000);
// 2. 第二种写法
function callback() {
console.log('two-爆炸了');
}
// 因为一个页面当中可能会有很多计时器,所以我们可以给计时器定义一个标识符
// var time1 = setTimeout(callback, 5000);
var time2 = setTimeout(callback, 5000);
// 停止定时器 clearTimeout(timeoutId) 参数为定时器的标识符
var btn = document.querySelector('button');
btn.addEventListener('click', function() {
clearTimeout(time2);
})
</script>
</body>
</html>

定时器setInterval
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="begin">开始定时器</button>
<button id="stop">停止定时器</button>
<script>
// 1. setInterval
// 语法规范: window.setInterval(调用函数, 延时时间);
// setInterval(function() {
// console.log('继续输出');
// }, 1000);
// 2. setTimeout 延时时间到了,就去调用这个回调函数,只调用一次 就结束了这个定时器
// 3. setInterval 每隔这个延时时间,就去调用这个回调函数,会调用很多次,重复调用这个函数
var begin = document.querySelector('#begin');
var stop = document.querySelector('#stop');
var timer = null;
begin.addEventListener('click', function() {
timer = setInterval(function() {
console.log('ni hao ma ');
}, 2000);
})
// 停止计时器 clearInterval(标识符)
stop.addEventListener('click', function() {
clearInterval(timer);
})
</script>
</body>
</html>
</html>
