更新時間:2021-11-12 來源:黑馬程序員 瀏覽量:
JavaScript在瀏覽器中是單線程執(zhí)行的,但允許使用定時器指定在某個時間之后或每隔一段時間就執(zhí)行相應的代碼。下面我們了解setTimeout()、clearTimeout()、setInterval()和clearInterval()的用法。
定時器方法 | |
方法 | 說明 |
| setTimeout() | 在指定的毫秒數(shù)后調用函數(shù)或執(zhí)行一段代碼 |
| setInterval() | 按照指定時間的周期(以毫秒計)來調用函數(shù) 或執(zhí)行一段代碼 |
| clearTimeout() | 取消由setTimeout()方法設置的定時器 |
| clearInterval() | 取消由setInterval()方法設置的定時器 |
setTimeout()和clearTimeout()
<script>
// 創(chuàng)建一個定時器,1000毫秒后執(zhí)行,返回定時器的標示
var timerId = window.setTimeout(function () {
console.log('Hello World');
}, 1000);
// 取消定時器的執(zhí)行
window.clearTimeout(timerId);
</script>setInterval()和clearInterval()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>setInterval</title>
</head>
<body>
<input type="button" value="取消定時器" id="btn">
</body>
<script>
// 創(chuàng)建一個定時器,每隔1秒調用一次
var timerId = window.setInterval(function () {
var d = new Date();
console.log(d.toLocaleTimeString());
}, 1000);
// 取消定時器
document.getElementById('btn').onclick = function(){
window.clearInterval(timerId);
}
</script>
</html>
猜你喜歡