JavaScript >> Javascript 文檔 >  >> JavaScript

如何在 JavaScript 中創建倒數計時器

本教程將演示如何在 JavaScript 中創建倒數計時器,包括一個可以復制並粘貼到自己代碼中的函數。

下面的代碼將分解創建一個計算直到某個未來時間的時間的函數,以及如何重複運行它以影響倒計時。

獲取到某個日期/時間的剩餘時間

以下函數將計算到目標日期的天、小時、分鐘和秒:

function timeToTarget(countdownString){

    // Convert the string which specifies the target to count down to to a Date object
    let targetDate = new Date(countdownString).getTime();

    // Get the current time
    let now = new Date().getTime();

    //The getTime() method gets a millisecond representation of the time since January 1st, 1970

    //Get the difference between the two
    let difference = targetDate - now;

    // Calculate the days, hours, minutes, seconds difference between the times
    days = Math.floor(difference / (1000 * 60 * 60 * 24));
    hours = Math.floor(difference / (1000 * 60 * 60));
    minutes = Math.floor(difference / (1000 * 60));
    seconds = Math.floor(difference / 1000);

    // Calculate the result
    // As each of the above is the total days, hours, minutes, seconds difference, they need to be subtracted so that they add up to the correct total
    let result =  {
        days: days,
        hours: hours - days * 24,
        minutes: minutes - hours * 60,
        seconds: seconds - minutes * 60,
    };

    // Log the result so we can check that the function is working
    console.log(result);

    // Return the result so that it can be used outside of the function
    return result;
}

使用 setInterval() 倒計時

JavaScript setInterval() 方法重複調用給定函數,運行之間有固定的時間延遲:

setInterval(function(){
    // Code to execute repeatedly here
}, 1000);

以上,函數timeToTarget() 每秒調用一次(1000 毫秒)。

顯示倒計時

要在網頁上顯示倒計時的結果,需要一個 HTML 元素:

<div id="countdown-display"></div>

然後可以使用以下 JavaScript 將倒計時信息寫入 HTML 元素:

document.getElementById("countdown-display").innerHTML =
    '<div>' + result.days + '<span>Days</span></div>' +
    '<div>' + result.hours + '<span>Hours</span></div>' +
    '<div>' + result.result + '<span>Minutes</span></div>' +
    '<div>' + result.seconds + '<span>Seconds</span></div>';

把它們放在一起

最後,需要將倒計時的日期/時間指定為字符串——這些數據可能來自日期選擇器或其他用戶輸入,或者來自數據庫:

var countdownString = "Feb 7, 2023 19:30:00";

把它們放在一起,一個工作倒計時!

var countdownString = "Feb 7, 2023 19:30:00";

function timeToTarget(countdownString){

    let targetDate = new Date(countdownString).getTime();
    let now = new Date().getTime();
    let difference = targetDate - now;

    days = Math.floor(difference / (1000 * 60 * 60 * 24));
    hours = Math.floor(difference / (1000 * 60 * 60));
    minutes = Math.floor(difference / (1000 * 60));
    seconds = Math.floor(difference / 1000);

    let result =  {
        days: days,
        hours: hours - days * 24,
        minutes: minutes - hours * 60,
        seconds: seconds - minutes * 60,
    };

    console.log(result);

    return result;

}

setInterval(function(){
    let result = timeToTarget(countdownString);
    document.getElementById("countdown-display").innerHTML =
        '<div>' + result.days + '<span> Days</span></div>' +
        '<div>' + result.hours + '<span> Hours</span></div>' +
        '<div>' + result.minutes + '<span> Minutes</span></div>' +
        '<div>' + result.seconds + '<span> Seconds</span></div>' +
        '<div><span>Until </span>' + countdownString + '</div>';

}, 1000);


Tutorial JavaScript 教程
  1. 使用 jQuery 將焦點放在第一個字段上

  2. 如何創建一個存儲唯一對象計數的 javascript 對象?

  3. React + Node.js + MySQL CRUD 示例

  4. JavaScript 混合

  5. 使用 React-router 和 Redux 征服導航狀態

  6. 如何在 ReactJS 中使用 Twitter 嵌入

  7. 增強您的開發知識的最重要的 Repos

  1. JavaScript 事件循環

  2. 頁面加載後執行 JavaScript | onload、document.onload 和 window.onload

  3. 在開源縮略圖庫 ReactJS 中生成視頻縮略圖。

  4. 為什麼 React 是前端開發的崇高

  5. 選擇 Node.js 框架的指南

  6. 直接提交到您的電子郵件地址的低代碼 HTML 表單! (免費無服務器表單)

  7. DOM 簡介

  1. Vue 應用程序的代碼覆蓋率

  2. JS .map() 和 .filter() 與 Code Witch

  3. 介紹 PromiViz - 可視化和學習 JavaScript Promise API

  4. Redux 困惑:Redux 到底是什麼?什麼是狀態?為什麼我們需要狀態管理器?