In JavaScript, you can create timer effects through the timed events setInterval and clearInterval. The setInterval method calls a function or calculates an expression according to a specified period.
The operating environment of this article: Windows 7 system, javascript version 1.8.5, Dell G3 computer.
Today I will share with you the knowledge about timers in JavaScript. It has certain reference value and I hope it will be helpful to everyone.
You can create a simple timer effect through the scheduled events setInterval and clearInterval() in JavaScript, which will be introduced in detail in the following article.
setInterval() method
is to call a function or calculate an expression according to the specified period (in milliseconds).
setInterval(code,millisec[,"lang"])
code: The function to be called or the code to be executed
millisec: The time interval between periodic execution or code calls, in milliseconds
If called If the setInterval() method is used, it will keep calling the function until the clearInterval() function appears or the window is closed, and the ID value returned by setInterval() can be used as a parameter of the clearInterval() method.
But there is a certain error in the timing of the setInterval() method
setTimeout() method
is used to call a function or after a specified number of milliseconds Calculate the expression, but only call it once. There is also the clearTimeout() method to clear setTimeout() to stop execution
Case sharing
Use the setInterval() method Write a timer within two minutes
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> input{ width:100px; height:40px; background:pink; color:#fff; font-size: 20px; text-align: right; } </style> </head> <body> 分钟:<input type="text" value="0"> 秒数:<input type="text" value="0"> <script src="tool.js"></script> <script> var minutes=document.getElementsByTagName("input")[0]; var seconds=document.getElementsByTagName("input")[1]; var minutes1=0; var seconds1=0; var timer=setInterval(function(){ //秒数自增,当秒数增加到60时分钟自增,秒数清零 seconds1++; if(seconds1==60) { seconds1=0; minutes1++; } minutes.value=minutes1; seconds.value=seconds1; if(minutes1==2)//到两分钟的时候定时器清除 { clearInterval(timer); } },100) </script> </body> </html>
Summary: The above is the entire content of this article. I hope it will be helpful for everyone to learn timed events.
The above is the detailed content of How to make a timer using scheduled events in JavaScript. For more information, please follow other related articles on the PHP Chinese website!