Sometimes, due to demand reasons, we need to write a method in JS and then let it be executed at a certain moment. That is, we need to write a timer in JS. When the time reaches the required time, the method that needs to be executed automatically Execution, let me briefly talk about how I implemented it
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 parameters hours and minutes in dingshi are the start time of the method to be executed. Here we only require hours and minutes. Under specific circumstances, you can add parameters by yourself, but be careful to modify the judgment conditions in the if in the run method.
getData is the method to be executed, and it can be modified according to the actual situation. Just call the dingshi method when using it.
Also note that in order to prevent the browser from crashing, I set the second parameter of setInterval to 3000 milliseconds, which is 3 seconds. If your timing requirements are accurate to seconds, you should change it to 1000, otherwise you may be missed. set time.