如何在给定的时间和日期运行函数?
例句:我有一个函数,需要在每个月12点上午10点运行。
如果这很重要的话,这个页面将全天候运行。
显然,我必须与当前日期进行比较,但我不知道如何检查当前日期和时间是否匹配。
香农
发布于 2013-09-30 08:00:44
不建议使用setInterval,因为它具有不确定的行为--事件可能会被忽略,或者一次性触发。时间也会不同步。
下面的代码使用有一分钟周期的setTimeout,每分钟计时器被重新同步,以便尽可能接近hh:mm:00.000点。
function surprise(cb) {
(function loop() {
var now = new Date();
if (now.getDate() === 12 && now.getHours() === 12 && now.getMinutes() === 0) {
cb();
}
now = new Date(); // allow for time passing
var delay = 60000 - (now % 60000); // exact ms to next minute interval
setTimeout(loop, delay);
})();
}发布于 2013-09-30 07:00:27
在o要进行检查的页面上添加以下内容
setInterval(function () {
var date = new Date();
if (date.getDate() === 12 && date.getHours() === 10 && date.getMinutes === 0) {
alert("Surprise!!")
}
}, 1000)小提琴
Update-添加date.getSeconds == 0以限制它在10:00只触发一次。感谢下面的评论
发布于 2013-09-30 06:59:33
可以实例化两个日期对象。一个是现在的,另一个是事件的下一个实例。现在很简单:新日期()。对于下一个实例,您可以遍历这些选项,直到找到比现在更大的选项。或者做一些更复杂的约会时间魔法。比较两者的getTime(),然后为警报执行setTimeout。
编辑:因为@Alnitak指出超时有一个最大值,所以更新了,请参阅如果延迟超过2147483648毫秒,setTimeout立即触发。
function scheduleMessage() {
var today=new Date()
//compute the date you wish to show the message
var christmas=new Date(today.getFullYear(), 11, 25)
if (today.getMonth()==11 && today.getDate()>25)
christmas.setFullYear(christmas.getFullYear()+1)
var timeout = christmas.getTime()-today.getTime();
if( timeout > 2147483647 ){
window.setTimeout( scheduleMessage(), 2147483647 )
} else {
window.setTimeout(function() {alert('Ho Ho Ho!'); scheduleMessage()}, timeout)
}
}https://stackoverflow.com/questions/19088040
复制相似问题