/**
* 检测是否能够刷新
* @param timeArray 刷新时间小时数组
* @param lastTime 上次的执行时间戳
* @returns {boolean}
*/
function checkRefreshAble(timeArray, lastTime){
var date = new Date(lastTime);
var hour = date.getHours();
var nextHour ;
for(var i = 0 ; i < timeArray.length; i++){
if(timeArray[i] > hour){
nextHour = timeArray[i];
break;
}
}
console.log('timeArray--->>',timeArray);
var currHour = new Date().getHours();
console.log('currHour:',currHour,' lastHour : ', hour, ' nextHour:',nextHour);
if(!nextHour){
nextHour = timeArray[0];
return currHour >= nextHour && currHour < timeArray[timeArray.length - 1];
}
return(currHour >= nextHour);
}
测试
var obj = {
time : 0
}
var timeArray = [0,4,12]; //每天凌晨 4点 12点执行任务
setInterval(function () {
//检测是否能够执行
var res = checkRefreshAble(timeArray, obj.time);
if(res){
console.log('refresh---->>>');
//todo 执行任务
obj.time = Date.now();
}
},2000);