This article mainly introduces in detail the basic method of implementing counters in JavaScript. , has a certain reference value, interested friends can refer to it
The example of this article shares the specific code of js implementation counter for your reference, the specific content is as follows
By using JavaScript executes code after a set interval, rather than immediately after the function is called. Call it a timing event.
It is very easy to use timing events in JavaScript. The two key methods are:
setInterval() - execute the specified event continuously for the specified number of milliseconds. code.
setTimeout() - Execute the specified code after pausing for the specified number of milliseconds
Note: setInterval() and setTimeout() are two methods of the HTML DOM Window object. Only the setTimeout() method is introduced here;
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script type="text/javascript"> var c = 0 var t function timedCount() { document.getElementById('txt').value = c; c = c + 1; //创建计时器,在指定周期内循环执行 t = setTimeout("timedCount()", 1000); } function stopCount() { //清除计时器 clearTimeout(t); } </script> </head> <body> <form> <input type="button" value="开始计时!" onClick="timedCount()"> <input type="text" id="txt"> <input type="button" value="停止计时!" onClick="stopCount()"> </form> </body> </html>
Effect:
Click start and it will Start counting from 0. If you stop the timing, it will pause at that moment. If you click start again, the counting will continue... But there is a small bug in this program. When you keep clicking to start timing, the timing speed will increase, and click once. Stopping the timer will not stop, it will take many responding clicks to stop...
The above is the detailed content of How to implement counter basics in JavaScript. For more information, please follow other related articles on the PHP Chinese website!