js如何設置一個倒計時

//申明一個定時器
let endInterval;
//結束時間(毫秒數,這裏是距離 1970 年 1 月 1 日至今的毫秒數)
let endSeconds;
//結束時間差
const ENDTIME = 10 * 1000;


window.onload = function () {
 
  //當頁面加載的時候,獲取當前加載頁面時刻的當前時間,再加上咱們須要的倒計時間,注意這裏全都是毫秒數,。
  endSeconds= new Date().getTime() + ENDTIME;

  //開始定時器
  endInterval = setInterval(timeItev, 500);
}

function timeItev() {

  //計算時間差,在定時器裏面不停獲取到新的new Date(),用end-new這個值就會一直變小
  let nowDate=new Date(endSeconds - new Date().getTime());
  //轉化爲分鐘和秒鐘
  let min = nowDate.getMinutes();
  let sec = nowDate.getSeconds();

  //把時間設置到你須要的標籤 上面
  $("#time").html(`${min}:${sec}`)

  if(min==0 && sec==0){
    clearInterval(endInterval)
    console.log("定時器結束")
  }
}
相關文章
相關標籤/搜索