</body> <script> var worker = new Worker("task.js"); worker.postMessage( { id:1, msg:'Hello World' } ); worker.onmessage=function(message){ var data = message.data; console.log(JSON.stringify(data)); worker.terminate(); }; worker.onerror=function(error){ console.log(error.filename,error.lineno,error.message); } </script> </html>
task.js
1 2 3 4 5
onmessage= function(message){ var data=message.data; data.msg = 'Hi from task.js'; postMessage(data); }
例子二: 计数功能
index.html
1 2 3 4 5 6 7 8 9 10 11 12 13
<script> var worker = new Worker("task.js"); worker.onmessage=function(message){ var data = message.data; console.log(JSON.stringify(data)); //终止woker //worker.terminate(); }; worker.onerror=function(error){ console.log(error.filename,error.lineno,error.message); } </script>
task.js
1 2 3 4 5 6 7 8
var i=0; functiontimedCount() { i=i+1; postMessage(i); setTimeout("timedCount()",500); } timedCount();