主要目标是与工作者进行主线程的最快(> 200fps)消息交换,无论该选项卡是否处于活动状态。
示例:
工人代码:
onmessage = function(rawMsg) {
var msg = rawMsg.data;
msg.state = "worker-THREAD:setInterval=>main-THREAD:onmessage=>worker-THREAD:onmessage";
msg.times.push( performance.now() );
postMessage(msg);
}
var sequenceNum = 0;
setInterval(function() {
var msg = {state:"", times: [], sequenceNum: sequenceNum++};
msg.state = "worker-THREAD:setInterval";
msg.times.push( performance.now() );
postMessage(msg);
}, 100);
主线程代码:
var worker = new Worker( 'js/test-worker.js' );
worker.onmessage = function(rawMsg) {
var msg = rawMsg.data;
switch( msg.state ) {
case "worker-THREAD:setInterval":
msg.state = "worker-THREAD:setInterval=>main:thread:onmessage";
msg.times.push( performance.now() );
worker.postMessage(msg);
break;
case "worker-THREAD:setInterval=>main-THREAD:onmessage=>worker-THREAD:onmessage":
show(msg);
break;
}
}
var lastSequenceNum = 0;
function show(msg) {
msg.times = msg.times.map(function(val) { return val / 1e3 });
if ( lastSequenceNum++ !== msg.sequenceNum ) {
alert("error sequence");
}
var ping = msg.times[2] - msg.times[0];
var isBad = ( ping > 0.01 );
var fx = 3;
var times = msg.times.map(function(val) { return val.toFixed(fx) });
console.log('#' + msg.sequenceNum + ' [ ' + times.join(', ') + ' ] ' + ping.toFixed(fx) + (isBad?' BAD!!!': ''));
}
var worker_Code = `
onmessage = function(rawMsg) {
var msg = rawMsg.data;
msg.state = "worker-THREAD:setInterval=>main-THREAD:onmessage=>worker-THREAD:onmessage";
msg.times.push( performance.now() );
postMessage(msg);
}
var sequenceNum = 0;
setInterval(function() {
var msg = {state:"", times: [], sequenceNum: sequenceNum++};
msg.state = "worker-THREAD:setInterval";
msg.times.push( performance.now() );
postMessage(msg);
}, 100);
`;
var worker = new Worker( window.URL.createObjectURL( new Blob( [worker_Code] ) ) );
worker.onmessage = function(rawMsg) {
var msg = rawMsg.data;
switch( msg.state ) {
case "worker-THREAD:setInterval":
msg.state = "worker-THREAD:setInterval=>main:thread:onmessage";
msg.times.push( performance.now() );
worker.postMessage(msg);
break;
case "worker-THREAD:setInterval=>main-THREAD:onmessage=>worker-THREAD:onmessage":
show(msg);
break;
}
}
var lastSequenceNum = 0;
function show(msg) {
msg.times = msg.times.map(function(val) { return val / 1e3 });
if ( lastSequenceNum++ !== msg.sequenceNum ) {
alert("error sequence");
}
var ping = msg.times[2] - msg.times[0];
var isBad = ( ping > 0.01 );
var fx = 3;
var times = msg.times.map(function(val) { return val.toFixed(fx) });
console.log('#' + msg.sequenceNum + ' [ ' + times.join(', ') + ' ] ' + ping.toFixed(fx) + (isBad?' BAD!!!': ''));
}
如果标签未处于活动状态,则消息会累积,并且一秒钟内就会出现“onmessage”。 我该如何解决这个问题?