Running interval timer with worker in Vue environment

Running interval timer with worker in Vue-Cli environment

Today, in code review, we found some problems left over before:
In a video playback page, there is a 40ms interval that has been blocking, resulting in a gradual increase in video delay.
So I wrote a worker and pulled the timer out and ran alone.

The implementation steps are as follows

Because vue-cli is used, it is necessary to install worker-loader dependencies under webpack to load worker.js separately.
npm install worker-loader --save-dev
Change the configuration items of the vue.config.js file
configureWebpack:{
    module: {
        rules: [
            {
                test: /\.worker\.js$/,
                loader: 'worker-loader',
                options: {
                  inline: true,
                  fallback: false,
                  name: '[name]:[hash:8].js'
                }
            }
        ]
    },
}

Note that the worker-loader configuration item must be written in front of js-loader, otherwise an error will be reported.

Write the encapsulation method below. In order to adapt to the multi-timer situation, you need to build a class class class.
/**
 * worker class
 * export Timer method
 * 
 */
export class workerTimer {
    constructor(){
         
    }
    timeInterval(name,interval,_this){
        console.log(name+'The timer has been set up');   
        this[name] = setInterval(() => {
            _this.postMessage({name:name,message:interval/1000+'Seconds arrived.'})
        },Number(interval))
    }
}
This class is then invoked using the worker main method, e for the incoming timer array within the component

import {workerTimer} from './workerTimer'
/**
 *Traversing parameters through traversers
 *new Create new worker classes
 *Call the timer method
 */
self.onmessage = function (e) {
    e.data.map((item) => {
      let workertimer = new workerTimer()
      workertimer.timeInterval(item.name,item.interval,self)
    })
};
Introducing worker into vue components
import Worker from './worker.js'
Write a method in methods, and the name starts at random.
workerInit(){
    this.worker = new Worker();
    this.worker.postMessage(this.workerList);
    this.worker.onmessage = (params) => {
        ...
    }
},
Create a variable in data in the following format:
workerList:[
    {name:'snapInterval',interval:10000},
    {name:'intervalFunc',interval:40}
],
Call the worker method within a hook
mounted(){
    this.workerInit()
}
Above, the work with two timers is set up, and callbacks can be triggered within the main thread by the name returned by the worker.
It's also easy to destroy the worker, just write it in the hook when destory happens.
this.worker.terminate();
that will do

Keywords: Front-end Vue Webpack npm

Added by Jonob on Sun, 13 Oct 2019 22:03:44 +0300