简体   繁体   English

在 JavaScript 中使用 setInterval 在特定时间执行代码块

[英]Executing a block of code at a certain time with a help of using setInterval in JavaScript

I want to execute a block of code in a certain time.我想在某个时间执行一段代码。 in order to do that I write a function called get_current which get the current time and by using setInterval and check the time in short interval, compare it to my desired time.为了做到这一点,我编写了一个名为get_current的 function ,它获取当前时间,并使用setInterval并在短时间内检查时间,将其与我想要的时间进行比较。 If that condition is satisfied I execute a console.log() .如果满足该条件,我将执行console.log()

I have tested the code below and got sure that the checkStart() is executed in the inteval which is defined in the code but unfortunately that if condition is never satisfied.我已经测试了下面的代码,并确保checkStart()在代码中定义的 inteval 中执行,但不幸的是if 条件永远不会满足。 Does anybody have any idea why?有人知道为什么吗?

var dateString;


function get_current(){

var mydate = new Date();
var mili_real = mydate.getMilliseconds();
var hour_real=mydate.getHours();
var minute_real=mydate.getMinutes();
var second_real=mydate.getSeconds();
     if(minute_real<10)minute_real="0"+minute_real;

     if(hour_real==0)hour_real="12";

     if(second_real<10) second_real="0"+second_real;
     if(mili_real<10)mili_real="00"+mili_real;
     else if(mili_real<100) mili_real="0"+mili_real;

     dateString=hour_real+""+minute_real+""+second_real+""+mili_real;
}

setInterval(checkStart,1);

function checkStart(){
    get_current();
    if(dateString==18581600){
    console.log("It's time to start");  
    }
}

Trying to hit an exact time with 1 millisecond accuracy will not work.试图以 1 毫秒的精度精确到准确的时间是行不通的。 Change:改变:

dateString==18581600

to:至:

dateString >= 18581600

Also, running setInterval with a 1 millisecond delay is not supported.此外,不支持以 1 毫秒延迟运行 setInterval。 4ms is the minimum, but it can be longer. 4ms 是最小值,但可以更长。

When in doubt, consult the MDN reference for setInterval() :如有疑问,请查阅MDN 参考以了解 setInterval()

[T]he browser will automatically enforce a 4 ms minimum value for the interval. [T] 浏览器将自动强制执行 4 ms 的最小值作为间隔。

Browsers may enforce even more stringent minimum values for the interval under some circumstances, although these should not be common.在某些情况下,浏览器可能会强制执行更严格的间隔最小值,尽管这些不应该是常见的。 Note also that the actual amount of time that elapses between calls to the callback may be longer than the given delay;另请注意,调用回调之间经过的实际时间量可能比给定的延迟长;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM