js 定时器有以下两个方法:
- setInterval() :按照指定的周期(以毫秒计)来调用函数或计算表达式。方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。
- setTimeout() :在指定的毫秒数后调用函数或计算表达式。
这里用的是setInterval
1、定义
在用定时器的时候,定义一个变量来记录定时器的返回值
let myInterval: any;
2、使用
myInterval = setInterval(() => {
}, 1000)
3、清除
回调函数在组件卸载后依旧调用。this将变成undefined,代码会报错。
warning.js?6327:33 Warning: setState(…): Can only update a mounted
or mounting component. This usually means you called setState() on an
unmounted component. This is a no-op. Please check the code for the
ResetPassword component.
react中可以在生命周期的componentWillUnmount
清除
componentWillUnmount() {
clearInterval(myInterval);
}