将特定数据传递给网络工作者

Passing specific data to webworkers

我有一个 WebWorker 为我计数,但我希望能够告诉它在我需要时减去特定数量(作为单一操作,即一次)。

当前代码:

var i = 0;

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

incrementMoney();

像这样使用某物:

// 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( );

然后,无论何时需要,您都可以通过 action 参数向 addsubtract 的工作人员发送消息(如果需要,您可以添加其他自定义操作并使用 "action messages" 让工作人员执行操作)

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