业务场景
一个考试系统,需要在用户切换窗口或者最小化的时候依然保持倒计时正常进行
技术
webWorker多线程
工具代码
function create(f) {
var blob = new Blob(['(' + f +')()']);
var url = window.URL.createObjectURL(blob);
var worker = new Worker(url);
return worker;
}
export const createWorker = (callback, time) => {
var pollingWorker = create(`function (e) {
setInterval(function () {
this.postMessage(null)
}, ${time})
}`);
pollingWorker.onmessage = callback
return pollingWorker;
}
export const stopWorker = (vm) => {
try {
vm&&vm.terminate()
} catch (err) {
console.log(err)
}
}
用法
// 引入
import {createWorker, stopWorker} from '...'
// 创建
const worker = createWorker(() => {
//做要做的事
}, 1000)
// 清除
/*
* worker的值还在这个不同于定时器
*/
stopWorker(worker)