Home > Web Front-end > JS Tutorial > How to display seconds in countdown timer in js

How to display seconds in countdown timer in js

下次还敢
Release: 2024-05-06 12:48:16
Original
935 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:

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

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>
Copy after login

HTML code:

<code class="html"><p id="timer"></p></code>
Copy after login

Working principle:

  1. Create variables and timers: Create a variable seconds to store seconds, and use the setInterval function to create a countdown timer, which is called every 1 secondcountdown function.
  2. countdown function: In the 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.
  3. Clear timer: When 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!

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 Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template