How to display seconds in countdown timer in js

下次还敢
Release: 2024-05-06 12:48:16
Original
803 people have browsed it

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 display seconds in countdown timer in js

How to implement a seconds display countdown timer in JavaScript

Create variables and timers:

let seconds = 10; // 初始秒数 let timer = setInterval(countdown, 1000); // 以 1 秒间隔调用 countdown 函数
Copy after login

countdown Function:

function countdown() { seconds--; // 减少秒数 let time = `${seconds}s`; // 转换为 "s" 格式 document.getElementById("timer").innerHTML = time; // 更新 HTML 中的计时器元素 // 当秒数为 0 时,清除计时器 if (seconds <= 0) { clearInterval(timer); } }
Copy after login

HTML code:

Copy after login

Working principle:

  1. Create variables and timers:Create a variablesecondsto store seconds, and use the setInterval function to create a countdown timer, which is called every 1 secondcountdownfunction.
  2. countdown function:In thecountdownfunction, decrementsecondsby one and convert it to the string "s" format. The updated time is then displayed in the HTML in atimerelement.
  3. Clear timer:Whensecondsreaches 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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!