Home > Article > Web Front-end > JS implements timer
This article mainly shares with you JS implementation of timer, mainly in the form of code, hoping to help everyone.
Problem description: Execute an event regularly
Mainly solve the problem of restarting
html
<body> <button id="btn1">start</button> <button id="btn2">stop</button> </body>
script
<script> window.addEventListener('load', my_timer, false); function my_timer() { let start = document.getElementById("btn1"); let stop = document.getElementById("btn2"); //计时函数 let timer = null; let eleClock = function () { timer = setInterval( function () { console.log(new Date()) }, 1000 ); }; //点击start按钮,开始定时器 start.onclick = function () { //do something eleClock(); }; //点击stop按钮,停止定时器 stop.addEventListener('click', function () { //do something window.clearInterval(timer); }, false); } </script>
Related recommendations:
JS implementation of animation timer method
Detailed explanation of JavaScript timer
The above is the detailed content of JS implements timer. For more information, please follow other related articles on the PHP Chinese website!