>本教程演示了一個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
let count = 10; let counter = setInterval(function() { count--; if (count < 0) { clearInterval(counter); return; } $("#timer").text(count + " secs"); }, 1000);a:使用
停止以>。 開始
clearInterval
問:如何恢復暫停的jQuery計時器?
setInterval
a:JavaScript不會直接恢復計時器。 使用當前計數值重新啟動它。
function pauseTimer() { clearInterval(counter); }
問:如何在jQuery中創建延遲的函數執行? a:jquery's
方法在動畫鏈中執行功能之前添加延遲。
setInterval
function resumeTimer() { counter = setInterval(function() { count--; if (count < 0) { clearInterval(counter); return; } $("#timer").text(count + " secs"); }, 1000); }a:
是重複執行函數的關鍵。 >
以上是使用settimeout製作jQuery計時器的詳細內容。更多資訊請關注PHP中文網其他相關文章!