简介:本文通过JavaScript中的语法讲解,js是如何实现定时器的开启与停止的。
学习代码:
<!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 class="begin">开启定时器</button>
<button class="stop">停止定时器</button>
<script>
// 首先获取元素
var begin = document.querySelector('.begin');
var stop = document.querySelector('.stop');
var timer = null; // 全局变量 null是一个空对象
// 给begin按钮添加事件
begin.addEventListener('click', function() {
// 给timer函数赋值
timer = setInterval(function() {
console.log(new Date())
}, 1000);
})
// 给stop按钮添加一个清空Inteterval的事件
stop.addEventListener('click', function() {
clearInterval(timer);
})
</script>
</body>
</html>