首页 > 解决方案 > 每天的日程安排功能

问题描述

我怎样才能让这个每天早上 8 点运行,而不仅仅是今天早上 8 点

var timeIsBeing936 = new Date("04/13/2021 08:00:00 AM").getTime()
   , currentTime = new Date().getTime()
   , subtractMilliSecondsValue = timeIsBeing936 - currentTime;
   setTimeout(getValue, subtractMilliSecondsValue);

标签: javascript

解决方案


您可以进行setTimeout“递归”(从技术上讲,它不是递归),以在触发前一个后再次调用调度程序函数。

注意:这是一个纯 JS 解决方案,因此它适用于所有环境,但由于setTimeout不准确,如果您需要高精度,这不是最佳选择。

function onTime(cb, h = 0, m = 0, s = 0, ms = 0){
  let id
  void function r(){
    let timeUntilNextOccurrence = new Date().setHours(h, m, s, ms) - Date.now()
    if(timeUntilNextOccurrence <= 0)
      timeUntilNextOccurrence += 86400000
    id = setTimeout(() => {
      cb()
      r()
    }, timeUntilNextOccurrence)
  }()
  return function cancel(){
    clearTimeout(id)
  }
}

const cancel = onTime(() => console.log("It's 8 am!"), 8, 0, 0)

您可以使用它返回的函数取消它。


推荐阅读