1. 程式人生 > >比較精確的js倒計時實現

比較精確的js倒計時實現

    // 傳入需要倒計時的秒數
    countDown(times) {
      // 時間間隔 1秒
      const interval = 1000;
      // 計算時間,轉化為毫秒
      let ms = times * 1000;
      let count = 0;
      const startTime = new Date().getTime();
      const endTime = startTime + ms;
      let timeCounter;
      timeCounter = setTimeout(countDownStart,
interval) function countDownStart() { count++ const offset = new Date().getTime() - (startTime + count * interval); // 計算剩餘時間 const diff = endTime - new Date().getTime(); const h = Math.floor(diff / (60 * 1000 * 60)); const hdiff = diff % (60 * 1000 * 60); const
m = Math.floor(hdiff / (60 * 1000)); const mdiff = hdiff % (60 * 1000); const s = mdiff / (1000); const sCeil = Math.ceil(s); const sFloor = Math.floor(s); let nextTime = interval - offset; if (nextTime < 0) { nextTime = 0 } ms = ms - interval;
console.log(`誤差:${offset} ms,下一次執行:${nextTime} ms 後,離活動開始還有:${ms} ms`); console.log('時:' + h, '分:' + m, '毫秒:' + s, '秒向上取整:' + sCeil) if (ms < 0) { clearTimeout(timeCounter) console.log('此處執行自己想要的操作') } else { timeCounter = setTimeout(countDownStart, nextTime) } } }

核心程式碼如上,可以更具自己的業務邏輯修改