我想知道如何通过使用jquery
或others jquery library
来检测或知道何时开始新的一天。
示例:
假设,现在是2016/06/23 23:59:50
。当second
进入2016/06/24 00:00:00
时,jquery
可以检测event
。
我知道我们可以使用setTimeOut
或setInterval
,并在新的一天到来时每秒检查一次。
但是我不想使用上面的这些方法,我们检测到哪些方法?
当日期更改时没有触发的自动事件。您可以做的是计算时间,直到日期更改为止,并在发生这种情况时使用setTimeout
运行功能。
var now = new Date;
var midnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
setTimeout(function() {
alert("It's tomorrow!");
}, midnight.getTime() - now.getTime());
new Date()
的参数是日期和时间的组成部分。省略时间参数将它们默认为0
。因此,将1添加到日期并省略时间将返回下一个午夜的时间。
您可以编写一个小的JavaScript类,该类不断采样时间并在发生事件发生时发射。您列出了jQuery,所以让我们用它来处理事件。
首先,让我们做一个样品的课程:
function DayChecker() {
var self = this;
// Get a copy of now to compare against
self.lastDate = new Date();
// A function that compares now to the lastDate, and fires the event
// if different, and resets the lastDate
self.sample = function() {
var tempDate = new Date();
// Compare the day component of the last sampled time to the
// current time
if (self.lastDate.getDay() != tempDate.getDay()) {
// It changed, so fire the event!
$(self).triggerHandler('daychange');
};
// Update the last sampled date so this can run forever and
// trigger on every day change
self.lastDate = tempDate;
}
// for illustration, a function that force changes the last date
// to trigger the event
self.forceChange = function() {
// Add 1 day to the last sample time to trip the event
self.lastDate.setTime(self.lastDate.getTime() + (1 * 86400000));
};
// Now start sampling every second (or whatever accuracy you need)
setInterval(self.sample, 1000);
};
现在我们创建了此助手类的新实例:
var dayChecker = new DayChecker();
听我称为" Daychange"的事件:
$(dayChecker).on('daychange', function() {
alert('new day!');
});
最后,运行几秒钟后为测试目的更改日期的功能:
setTimeout(function() {
// Testing only!
dayChecker.forceChange();
}, 5000);
您应该在五秒钟后看到警报。
a jsfiddle