HTML
setInterval() setInterval() method calls a function at specified intervals (in milliseconds). 方法可按照指定的周期(以毫秒計)來調用函數或計算表達式。 setInterval(function, milliseconds, param1, param2, ...) setInterval(function, 毫秒, 參數1, 參數2, ...) clearInterval(myInterval) clearInterval() to stop the time 停止時間 Example: var myInterval=setInterval(........) clearInterval(myInterval)
<p id="demo"></p> <script> var txt="" , ii=0; if(Stop){ clearInterval(myInterval) } var Stop = setInterval(TX, 1000); function TX() { ii++ ; txt += " [RUN " + ii +"] " ; demo.innerHTML = txt ; if(ii > 19){ clearInterval(Stop) ; demo.innerHTML += " clearInterval(Stop)";} } </script> result :
<p id="demo"></p> <script> if(myInterval){ clearInterval(myInterval) } var myInterval = setInterval(myTimer, 1000); function myTimer() { const date = new Date(); demo.innerHTML = date.toLocaleTimeString(); } </script> result :