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
    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 {
        console.log(name+'The timer has been set up');   
        this[name] = setInterval(() => {
            _this.postMessage({name:name,message:interval/1000+'Seconds arrived.'})
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) { => {
      let workertimer = new workerTimer()
Introducing worker into vue components
import Worker from './worker.js'
Write a method in methods, and the name starts at random.
    this.worker = new Worker();
    this.worker.onmessage = (params) => {
Create a variable in data in the following format:
Call the worker method within a hook
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.
that will do

Keywords: Front-end Vue Webpack npm

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