Toggle navigation
集客麦麦@谢坤
首页
随笔
首页
>>
创作中心
>>
JS 多线程 We...
JS 多线程 WebWorkers 示例操作
Not Found
在看示例之前你需要了解的基础知识: ## Web Workers 当在 HTML 页面中执行脚本时,页面的状态是不可响应的,直到脚本已完成。 web worker 是运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。您可以继续做任何愿意做的事情:点击、选取内容等等,而此时 web worker 在后台运行。 ## postMessage() ------ ## 定义和用法 postMessage() 方法用于安全地实现跨源通信。 ## 语法 ```javascript otherWindow.postMessage(message, targetOrigin, [transfer]); ``` | 参数 | 说明 | | ------------ | ------------------------------------------------------------ | | otherWindow | 其他窗口的一个引用,比如 iframe 的 contentWindow 属性、执行 window.open 返回的窗口对象、或者是命名过或数值索引的 window.frames。 | | message | 将要发送到其他 window的数据。 | | targetOrigin | 指定哪些窗口能接收到消息事件,其值可以是 *(表示无限制)或者一个 URI。 | | transfer | 可选,是一串和 message 同时传递的 Transferable 对象。这些对象的所有权将被转移给消息的接收方,而发送一方将不再保有所有权。 | ------ demo_workers.js ```javascript console.log('slave start') var i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()",500); console.log('slave start aaaaaaa') } timedCount(); ``` test.html ```html
Count numbers:
Start Worker
Stop Worker
```