Home > Web Front-end > JS Tutorial > Customize a timer in JS to execute it at a certain moment_javascript tips

Customize a timer in JS to execute it at a certain moment_javascript tips

WBOY
Release: 2016-05-16 16:37:54
Original
1171 people have browsed it

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(); //要执行的方法 
} 
} 
}
Copy after login

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.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template