Custom timer in JS to be executed at a certain time

  • 2020-03-30 03:50:25
  • OfStack

Sometimes, for reasons of demand, we need to write a method in JS, and then let it execute at a certain time, that is, we need to write a timer in JS, when the time reached the required time, the method that needs to be executed automatically, the following site simply said how I implemented


var tMinutes=0; 
var tHours=0; 
var go; 
function dingshi(hours,minutes){ 
tHours = hours; 
tMinutes = minutes; 
go=setInterval(run,3000); 
} 
function run(){ 
var date=new Date(); 
if((date.getMinutes()-tMinutes==0) 
&&(date.getHours()-tHours==0)){ 
clearInterval(go); 
getData(); //The method to be executed
} 
} 
}

In dingshi, the parameter "hours", "minutes" is the beginning time of the method to be executed, which only requires hours and minutes. In this case, you can add parameters by yourself, but you should pay attention to modify the judgment condition of if in the run method.

GetData is the method to be executed, is also modified according to the actual situation, when the use of dingshi method can be called.

Another thing to note is that in order to prevent the browser from crashing, the second parameter of setInterval I'm going to set it at 3000 milliseconds, which is 3 seconds, and if you want it to be accurate to seconds, I'm going to change it to 1000, otherwise I might miss your time.


Related articles: