如何在setInterval()中使用localtime?

时间:2017-04-18 21:21:56

标签: javascript

我每隔5分钟使用setInterval(5*60*1000)来调用我的功能,但问题是如果我在00.03AM打开我的网页,那个函数将被调用的时间是00.08AM。

所以,我希望我的功能被称为跟随当地时间,我的意思是现实生活中的时间。例如,如果我在00.03AM打开我的网页,则会每5分钟调用一次该函数,例如00.05AM, 00.010AM, 00.015AM, ...

或者,换句话说,如何让我的功能在一小时内的下一个5分钟运行,然后每隔5分钟运行一次。 请建议我如何做那件事。谢谢。

2 个答案:

答案 0 :(得分:3)

我要做的是每分钟检查一次,但是如果时间是5分钟的倍数,则只执行一些操作。像这样:

setInterval(function() {
  if(new Date().getMinutes() % 5 == 0){
    // Do something
  }
}, 60*1000)

答案 1 :(得分:0)

确定到下一个五点的距离,然后从该点开始点击事件。



var dateNow = new Date(Date.now());
var currentMinute = parseInt(dateNow.getMinutes().toString()[1]);
var currentSecond = dateNow.getSeconds();

var timer1;
var secsUntilNextFive = 5;

console.log("Minutes is: " + currentMinute);
console.log("Seconds is: " + currentSecond);

if (currentMinute===5 || currentMinute===0)
{
    secsUntilNextFive = 1;
}
else if (currentMinute<5)
{  
    secsUntilNextFive = (5-currentMinute) * 60; 
}
else if (currentMinute>5)
{
    secsUntilNextFive = (10-currentMinute) * 60;
}
// Now subtract the mins already elapsed towards next goal
secsUntilNextFive -= currentSecond;

console.log("Timer will kickoff in: " + secsUntilNextFive + "seconds");

DoAction(); // Do the first time or you can wait until the timer goes off

setTimeout(function(){

  console.log("Starting timer now...");
//Start the interval to now start every 5
  timer1 = setInterval(DoAction, 60*1000*5);
  
}, secsUntilNextFive*1000);

function DoAction() {
    console.log("Doing a task...");
}
&#13;
&#13;
&#13;

相关问题