2017-04-18 39 views
0

我使用setInterval(5*60*1000)每5分钟拨打我的电话号码,但问题是如果我在00.03AM打开我的网页,功能将被调用的时间是00.08AM。如何使用localtime和setInterval()?

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

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

+0

取决于你想要如何精确的是,考虑在一分钟的间隔运行的功能,并且使其检查,看看是否当前时间是五个 – Hamms

回答

3

我要做的是每分钟检查一次,但只有在时间为5分钟的倍数时才执行。类似这样的:

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

的倍数非常感谢你。有用 !!!。但是有一些延迟2到3秒之前(有时会)再次调用函数。因此,我添加了更多功能:'if(new Date()。getSeconds()== 0)'正好5分钟调用该函数。 – Nothingnez

+0

如果你这样做了,不要忘记你需要'setInterval'来运行每一秒! –

+0

是的,我做到了。再次感谢你 :) – Nothingnez

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..."); 
 
}