首頁 >web前端 >js教程 >使用settimeout製作jQuery計時器

使用settimeout製作jQuery計時器

Joseph Gordon-Levitt
Joseph Gordon-Levitt原創
2025-03-06 01:11:10294瀏覽

Using SetTimeout to Make a jQuery Timer

>本教程演示了一個jQuery倒計時計時器,該計時器從每秒10個降低。 這是通過在計時器函數中遞歸調用setTimeout來實現的。以下是代碼。

jQuery Code

jQuery(document).ready(function() {

    let countdown;
    let countdownNumber;

    function countdownInit() {
        countdownNumber = 11;
        countdownTrigger();
    }

    function countdownTrigger() {
        if (countdownNumber > 0) {
            countdownNumber--;
            $('#countdown_text').html(countdownNumber); //Corrected selector and method
            if (countdownNumber > 0) {
                countdown = setTimeout(countdownTrigger, 1000); //Simplified setTimeout call
            }
        }
    }

    function countdownClear() {
        clearTimeout(countdown);
    }

    countdownInit(); //Start the timer on page load

});

> html代碼

<div id="countdown_text">Placeholding text</div>

經常詢問有關jQuery計時器的問題

本節解決了有關jQuery計時器的常見問題。

問:如何使用jQuery構建倒數計時器? a:使用以設定的間隔重複執行。 這是一個簡潔的例子:

setInterval

問:如何暫停jQuery Timer?
let count = 10;
let counter = setInterval(function() {
    count--;
    if (count < 0) {
        clearInterval(counter);
        return;
    }
    $("#timer").text(count + " secs");
}, 1000);
a:使用

停止以>。 開始

clearInterval問:如何恢復暫停的jQuery計時器? setIntervala:JavaScript不會直接恢復計時器。 使用當前計數值重新啟動它。

>
function pauseTimer() {
    clearInterval(counter);
}

問:如何在jQuery中創建延遲的函數執行? a:jquery's

方法在動畫鏈中執行功能之前添加延遲。 >

setInterval

問:如何在jQuery中創建重複計時器?
function resumeTimer() {
    counter = setInterval(function() {
        count--;
        if (count < 0) {
            clearInterval(counter);
            return;
        }
        $("#timer").text(count + " secs");
    }, 1000);
}
a:

是重複執行函數的關鍵。 >

以上是使用settimeout製作jQuery計時器的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn