Search code examples
web-worker

Passing specific data to webworkers


I have a WebWorker counting up for me, but I want to be able to tell it to subtract by a specific amount (as single action, i.e once) whenever I want.

Current code:

var i = 0;

    function incrementMoney() {
      i = i + 1;
      postMessage(i);
      setTimeout("incrementMoney()",1000);
    }

incrementMoney();

Solution

  • use sth like this:

    // worker script
    var x = 0, dx = 1, current_action='add';
    var actions = {
    'add': function( ) { x += dx; },
    'subtract': function( ) { x -= dx; }
    };
    
    onmessage = function( evt ) {
       if ( evt.data && evt.data.action && evt.data.action in actions)
       {
         if ( true === evt.data.once )
         {
             // store current state
             var prev_action = current_action, prev_dx = dx;
             current_action = evt.data.action;
             if ( null != evt.data.amount ) dx = evt.data.amount;
             // do action once,
             // optionaly, you can also stop the "doAction timer"
             // and restart it after finishing this action, ie below
             // but left it as is for now
             actions[current_action]( );
             // restore state
             current_action = prev_action;
             dx = prev_dx;
         }
         else
         {
             current_action = evt.data.action;
             if ( null != evt.data.amount ) dx = evt.data.amount;
         }
       }
    };
    
    function doAction( )
    {
       actions[current_action]( );
       postMessage( x );   
       setTimeout(doAction,1000);
    }
    
    doAction( );
    

    Then whenever you need you send a message to your worker with an action parameter to either add or subtract (you can add other custom actions if needed and use "action messages" to get worker to do the action)

    // main script
    myworker.postMessage({action:'subtract', amount:5, once:true});