簡述
在《JavaScript高級程序設計(第三版)》中,提到WebWorker的importScripts方法是異步執行的,然而在
另一本書《Javascript權威指南》中,卻說importScripts是一個同步方法,兩者矛盾,故私底下測試一番,發現
該方法確實是同步執行,待所有js問價解析執行完畢再執行后續代碼。
另外,importScripts方法是可以嵌套執行的。
如:
index.html:
<script> var w = new Worker("worker1.js"); w.onmessage = function(e){ console.log(e.data) } w.postMessage("from index ...") </script>
work1.js:
importScripts("t1.js"); console.log("worker1.js"); onmessage = function(e){ console.log(e.data) }
t1.js:
importScripts("t2.js") console.log("this is the t1.js ...")
t2.js:
console.log("this is the t2.js ...")
返回結果:
this is the t2.js ... this is the t1.js ... worker1.js from index ...
其他
worker線程,同步運行代碼,當worker線程並沒有綁定onmessage事件處理程序並且沒有其他異步回調或者定時器外,代碼執行完畢就銷毀該線程。如果線程沒有onmessage,但是有異步回調,則等待回調執行。