setTimeout() ⇒ function in javascript allows you to schedule the execution of a function after an amount of time (milliseconds).
Times are approximate(varies based on the workload of the javascript runtime env.)
setTimeout(callback, delay); setInterval(callback, repeatTime)
setInterval()会重复执行一项指令, 用法和setTimeout()一样
案例: 启动定时器和清除定时器
<!-- ======================== HTML 结构 ======================== -->
<!-- 点击按钮后触发 JavaScript 函数 -->
<button onclick="setTimer()">start</button>
<button onclick="clearTimer()">clean</button>
<script>
// ======================== 定义全局变量 ========================
// 用于保存 setTimeout() 返回的定时器 ID
// 有了这个 ID 才能在之后清除该定时器
let timeoutId;
// ======================== 启动定时器 ========================
function setTimer(){
// setTimeout() 用于“延迟执行”某个函数
// 语法:setTimeout(函数, 延迟时间毫秒)
// 这里延迟 3000 毫秒(3 秒)后执行箭头函数
// 箭头函数执行时会输出 “3000ms pass”
timeoutId = setTimeout(() => console.log("3000ms pass"), 3000);
// 这行代码会立即执行,不会等待 3 秒
console.log("start");
}
// ======================== 清除定时器 ========================
function clearTimer(){
// clearTimeout() 可以根据定时器 ID 清除未执行的延时任务
// 如果在 3 秒内点击了“clean”按钮,原本的 setTimeout 就不会再触发
clearTimeout(timeoutId);
console.log("cleaned");
}
</script>