js封装定时器多个组件使用
时间: 2024-01-10 09:01:02 浏览: 29
在JavaScript中,可以通过封装定时器来实现多个组件的定时功能。以下是一个简单的例子:
```javascript
// 定义一个封装了定时器的组件
function TimerComponent(interval, callback) {
this.interval = interval; // 定时器间隔时间
this.callback = callback; // 定时器回调函数
this.timerId = null; // 定时器Id
}
// 启动定时器
TimerComponent.prototype.start = function() {
// 判断定时器Id是否已存在,如果存在则表示已启动过,不再重复启动
if (this.timerId) {
return;
}
// 使用箭头函数确保回调函数内部使用正确的this对象
this.timerId = setInterval(() => {
// 调用回调函数
this.callback();
}, this.interval);
}
// 停止定时器
TimerComponent.prototype.stop = function() {
// 清除定时器Id
clearInterval(this.timerId);
this.timerId = null;
}
// 创建多个定时器组件实例
var timer1 = new TimerComponent(1000, function() {
console.log("定时器1触发");
});
var timer2 = new TimerComponent(2000, function() {
console.log("定时器2触发");
});
// 启动定时器
timer1.start();
timer2.start();
// 停止定时器
// timer1.stop();
// timer2.stop();
```
以上代码中,我们定义了一个`TimerComponent`对象,该对象包含了一个定时器的间隔时间和回调函数,并且提供了启动和停止定时器的方法。通过创建多个`TimerComponent`实例,每个实例都可以设置不同的定时器间隔和回调函数。调用`start`方法可以启动定时器,调用`stop`方法可以停止定时器。这样,我们就可以通过封装定时器来实现多个组件的定时功能。