当前位置: 首页> 科技> 互联网 > vue2中使用web worker启动定时器

vue2中使用web worker启动定时器

时间:2025/7/11 0:56:18来源:https://blog.csdn.net/xinshijimanon/article/details/142149860 浏览次数:0次

vue2中使用web worker启动定时器,避免浏览器最小化或切换标签页时定时器不能按设定周期执行【一般是周期小于60s时,大于60s一般可正常执行】

  • 1、添加worker-loader
  • 2、修改vue.config.js
  • 3、创建timer.worker.js
  • 4、创建TimerWorker.js
  • 5、使用TimerWorker启动定时任务

1、添加worker-loader

npm install worker-loader --save

2、修改vue.config.js

新增以下配置

 config.module.rule('workers').test(/\.worker\.js$/).use('worker-loader').loader('worker-loader').options({inline: 'fallback'  // 尝试内联,失败则回退到默认行为})

3、创建timer.worker.js

self.timers = {}self.onmessage = function(event) {const { action, id, interval } = event.dataswitch (action) {case 'startTimer':startTimer(id, interval)breakcase 'stopTimer':stopTimer(id)breakcase 'stopAllTimers':stopAllTimers()break}
}function startTimer(id, interval) {if (!self.timers[id]) {self.timers[id] = setInterval(() => {self.postMessage({ id })}, interval)}
}function stopTimer(id) {if (self.timers[id]) {clearInterval(self.timers[id])delete self.timers[id]}
}function stopAllTimers() {Object.keys(self.timers).forEach(id => {clearInterval(self.timers[id])})self.timers = {}
}

4、创建TimerWorker.js

import Worker from './timer.worker.js'export default class TimerWorker {worker;timers;constructor() {this.start()}startTimer(id, interval, fun) {if (this.worker && !this.timers[id]) {this.timers[id] = funthis.worker.postMessage({ action: 'startTimer', id, interval })}return this}stopTimer(id) {if (this.worker && this.timers[id]) {this.worker.postMessage({ action: 'stopTimer', id })delete this.timers[id]}return this}stopAllTimers() {if (this.worker) {this.worker.postMessage({ action: 'stopAllTimers' })this.timers = {}}return this}start() {if (!this.worker) {const worker = new Worker()worker.onmessage = (event) => {this.timers[event.data.id]()}this.worker = workerthis.timers = {}}return this}terminate() {if (this.worker) {this.stopAllTimers()this.worker.terminate()this.worker = undefinedthis.timers = undefined}return this}
}

5、使用TimerWorker启动定时任务

import TimerWorker from './TimerWorker'export default {...created() {this._timerWorker = new TimeWorker()this.startTimer()},beforeDestroy() {this._timerWorker.terminate()},methods: {startTimer() {this._timeWorker.startTimer('test', 100, () => {console.log(new Date().getTime())})}}...
}
关键字:vue2中使用web worker启动定时器

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: