首頁技術(shù)文章正文

js定時(shí)器怎么用?如何設(shè)置和取消定時(shí)器?

更新時(shí)間:2021-11-12 來源:黑馬程序員 瀏覽量:

JavaScript在瀏覽器中是單線程執(zhí)行的,但允許使用定時(shí)器指定在某個(gè)時(shí)間之后或每隔一段時(shí)間就執(zhí)行相應(yīng)的代碼。下面我們了解setTimeout()、clearTimeout()、setInterval()和clearInterval()的用法。


定時(shí)器方法

方法

說明

setTimeout()在指定的毫秒數(shù)后調(diào)用函數(shù)或執(zhí)行一段代碼
setInterval()按照指定時(shí)間的周期(以毫秒計(jì))來調(diào)用函數(shù)
或執(zhí)行一段代碼
clearTimeout()取消由setTimeout()方法設(shè)置的定時(shí)器
clearInterval()取消由setInterval()方法設(shè)置的定時(shí)器

setTimeout()和clearTimeout()

<script>
    // 創(chuàng)建一個(gè)定時(shí)器,1000毫秒后執(zhí)行,返回定時(shí)器的標(biāo)示
    var timerId = window.setTimeout(function () {
        console.log('Hello World');
    }, 1000);

    // 取消定時(shí)器的執(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="取消定時(shí)器" id="btn">
</body>
<script>
    // 創(chuàng)建一個(gè)定時(shí)器,每隔1秒調(diào)用一次
    var timerId = window.setInterval(function () {
        var d = new Date();
        console.log(d.toLocaleTimeString());
    }, 1000);

    // 取消定時(shí)器
    document.getElementById('btn').onclick = function(){
        window.clearInterval(timerId);
    }

</script>
</html>

1636699552174_取消定時(shí)器.gif



猜你喜歡

jQuery和vue的區(qū)別是什么?

jQuery中attr()和prop()有什么不同?

jQuery元素內(nèi)容操作的方法有多少種?

黑馬程序員web前端培訓(xùn)課程

分享到:
在線咨詢 我要報(bào)名
和我們在線交談!