Search code examples
javascripthtmlweb-worker

HTML5 WebWorker send & receive Number


  1. How to send a number to webworker?

  2. How to receive a number in webworker?

if possible, How to do this without using JSON or JavaScript Object, because using it will add extra line of code ..

I try to create timer in webworker

  • if I send string "start" to webworker, webworker will begin the interval( the timer )
  • if I send a number to webworker, webworker will set the duration of interval

but I don't know how to send a number,

I knew argument passed to webworker should be a string, I already read few tutorial,

but I still don't understand what to do so my webworker can recognize a number..

because I try parseInt() and is not work ..

Here's my code

in HTML

window.onload = function(){
            
            var worker = new Worker("Thread.js");
            worker.postMessage("1500");     //set duration of interval
            worker.postMessage("start");    //start the interval
            
            
            worker.onmessage = function(e){
                document.body.innerHTML += '<p> worker receive: '+e.data+'</p>';
            }
            
            worker.onerror = function(e){
                document.body.innderHTML += "<p> worker error"+e.data+"</p>";
            }
            
    }

Thread.js

onmessage = function(e){

    var msg =  e.data ;
    var timer;
    var duration = 1000;    //default duration
    
    try{
        var number = parseInt(msg);
        msg = number;
    }catch(e){
        
    }
    
    //start the interval
    if(msg === "start"){
        timer = setInterval(function(){
            postMessage( "lalala" );
        }, duration);
    }
    
    else if(msg === "stop"){
        clearInterval(timer);
    }
    
    //set duration
    else if(!isNaN(msg)){
        duration = msg;
    }
    
    
}

Solution

  • That doesn't work because parseInt doesn't throw an Error, it returns NaN (Not a Number).

    You also have another bug: you need to declare timer and duration outside onmessage if you want both to persist between two messages.

    Note that changing duration won't affect the interval unless you restart it.

    var timer;
    var duration = 1000;
    
    onmessage = function(e) {
        var msg = e.data ;
        var number = parseInt(msg);
    
        if(msg === "start") {
            timer = setInterval(function() {
                postMessage( "lalala" );
            }, duration);
        } else if(msg === "stop") {
            clearInterval(timer);
        } else if(!isNaN(msg)) {
            duration = number;
        }
    };