How to implement a seconds display countdown timer in JavaScript: Create the variable seconds to store the seconds. Create a timer that calls the countdown function at 1 second intervals. In the countdown function, decrement the seconds and update the time in the HTML timer element. When the seconds reaches 0, clear the timer.
How to implement a seconds display countdown timer in JavaScript
Create variables and timers:
<code class="js">let seconds = 10; // 初始秒数 let timer = setInterval(countdown, 1000); // 以 1 秒间隔调用 countdown 函数</code>
countdown Function:
<code class="js">function countdown() { seconds--; // 减少秒数 let time = `${seconds}s`; // 转换为 "s" 格式 document.getElementById("timer").innerHTML = time; // 更新 HTML 中的计时器元素 // 当秒数为 0 时,清除计时器 if (seconds <= 0) { clearInterval(timer); } }</code>
HTML code:
<code class="html"><p id="timer"></p></code>
Working principle:
seconds
to store seconds, and use the setInterval function to create a countdown timer, which is called every 1 secondcountdown
function. countdown
function, decrement seconds
by one and convert it to the string "s" format. The updated time is then displayed in the HTML in a timer
element. seconds
reaches 0, use clearInterval to clear the timer and stop the countdown. The above is the detailed content of How to display seconds in countdown timer in js. For more information, please follow other related articles on the PHP Chinese website!