Article directory
The js timer has the following two methods: setTimeout()
andsetInterval()
1 setTimeout(): delay timer
Executed only once after the specified number of milliseconds .
1.1 open
The specified time is 6000 milliseconds, that is, 6s. After reaching 6s, it will be executed only once, and will not be executed after that.
const func = () => {
console.log('hello') };
const timer = setTimeout(func, 6000); // 两个参数分别是:要执行的方法与时间
1.2 Clear
// 在开启定时器的同时定义一个变量来接收定时器返回的id,用于清除定时器。
clearTimeout(timer);
2 setInterval(): cycle timer
Repeatedly calls a method at regular intervals .
2.1 open
const func = () => {
console.log('循环!!!') };
const timer = setInterval(func, 6000); // 指定时间为 6s,每6s执行一次
2.2 Clear
clearInterval(timer);