Web worker Integration

孤者浪人 提交于 2020-02-06 07:37:09

问题


I want to use web worker to handle my zipcode checker function, I haven't worked with web worker before so the concept is new to me

This is my zipcode function

``

function checkZipCode() {
    event.preventDefault();

    if(document.getElementById('zipcode').value < 20000) {
        document.getElementById('zip-result').innerHTML = 'Sorry, we haven’t expanded to that area yet';

    } else if (document.getElementById('zipcode').value >= 20000) {
        document.getElementById('zip-result').innerHTML = 'We’ve got your area covered!'
    } else {
        return null
    }
};

回答1:


As per the docs workers are pretty easy to spin up:

//in a JS file
const myWorker = new Worker('./myWorker.js');//worker requested and top-level scope code executed

myWorker.postMessage('hello');

myWorker.addEventListener('message', e => {
  //e.data will hold data sent from worker
  const message = e.data;
  console.log(message); // HELLO
  //if it's just a one-time thing, you can kill the worker
  myWorker.terminate();
}

myWorker.addEventListener('error', e => {//worker might throw an error
  e.preventDefault();
  console.log(e.message, `on line ${e.lineno}`);
});


//myWorker.js

//run whatever you need, just no DOM stuff, no window etc
console.log('this line runs when worker loads');

addEventListener('message', (e) => {
    postMessage(e.data.toUpperCase());//up-case message and send it right back
});




来源:https://stackoverflow.com/questions/57532356/web-worker-integration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!