-
在JavaScript中有两种定时器, 一种是重复执行的定时器, 一种是只执行一次的定时器
<button id="start">开始</button>
<button id="close">结束</button>
-
1. 重复执行的定时器
// 第一个参数接收一个函数, 第二个参数接收毫秒值 setInterval(function () { console.log("随便写点"); }, 1000);
-
添加点击事件
// 开始 let startBtn = document.querySelector("#start"); let id = null; startBtn.onclick = function () { id = setInterval(function () { console.log("随便写点"); }, 1000); } // 关闭 let closeBtn = document.querySelector("#close"); closeBtn.onclick = function () { clearInterval(id); }
-
-
2. 只执行一次的定时器
// 第一个参数也接收一个函数, 第二个参数也接收毫秒值 setTimeout(function () { console.log("随便写点"); },1000);
-
添加点击事件
// 开始 let startBtn = document.querySelector("#start"); let id = null; startBtn.onclick = function () { id = window.setTimeout(function () { console.log("随便写点"); },5000); }; // 关闭 let closeBtn = document.querySelector("#close"); closeBtn.onclick = function () { clearTimeout(id); };
-
网友评论