javascript - 每天的日程安排功能
问题描述
我怎样才能让这个每天早上 8 点运行,而不仅仅是今天早上 8 点
var timeIsBeing936 = new Date("04/13/2021 08:00:00 AM").getTime()
, currentTime = new Date().getTime()
, subtractMilliSecondsValue = timeIsBeing936 - currentTime;
setTimeout(getValue, subtractMilliSecondsValue);
解决方案
您可以进行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)
您可以使用它返回的函数取消它。
推荐阅读
- css - (React-redux 前端开发)我应该使用 css 还是添加另一个框架?
- html - 如何将表格行拆分为两列?
- javascript - 带有外部文件的 Javascript 和 json 语句循环
- azure - 如何将不同的自定义技能组映射到索引
- android - 从 jetpack compose 中的另一个小部件访问小部件
- c# - bot框架c#中的自定义选项卡
- android - 添加后在文本和选取器行之间出现大的空白
- javascript - 当我输入长度为 4 的值但返回所有其他值的正确长度时,我的 if 语句返回 0 作为变量的长度
- reactjs - 将类型添加到被设置为路由组件的解构反应组件属性?
- javascript - 如何在带有 yield 的生成器中使用 Array.prototype.reduce?