Javascript setInterval


function displayTime() {
   let date = new Date();
   let time = date.toLocaleTimeString();
   document.getElementById('demo').textContent = time;
}

const createClock = setInterval(displayTime, 1000);

clearing intervals

const myInterval = setInterval(myFunction, 2000);

clearInterval(myInterval);



  • You probably ought to disable the start button after pressing it once, and enable it again after you've stopped/reset it. Otherwise multiple presses of the start button will apply multiple setInterval()s to the clock, leading to wrong behavior.

start按钮按过之后,disable the start button 禁止点start按钮,持续的点击会导致多个 setInterval() 可能就乱了。
先按stop和reset后,在里面执行clearInterval() 清除掉这个记时。


阅读量: 575
发布于:
修改于: