SoFunction
Updated on 2025-03-09

Custom timer in JS to enable it to be executed at a certain moment

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((()-tMinutes==0) 
&&(()-tHours==0)){ 
clearInterval(go); 
getData(); // Method to be executed} 
} 
}

In the parameters hours in dingshi, minutes are the time when the method to be executed starts. Here are only hours and minutes. In specific cases, you can add parameters by yourself, but pay attention to modifying the judgment conditions in if in the run method.

getData is the method to be executed, and it is also modified by itself according to the actual situation. You can just call the dingshi method when using it.

Also note that in order to prevent browser crashes, I set the second parameter of setInterval to 3000 milliseconds, that is, 3 seconds. If everyone requires the exact time to be as accurate as seconds, it should be changed to 1000 here, otherwise you may miss the time you set.