
然后我写了一下代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" cOntent="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" cOntent="ie=edge" /> <title>任务队列</title> <style> #aa { width: 100px; height: 100px; background: green; } </style> </head> <body> <div id="aa"></div> </body> <script> // 动画 var start = null; var element = document.getElementById('aa'); element.style.position = 'absolute'; function step(timestamp) { if (!start) start = timestamp; var progress = timestamp - start; element.style.left = Math.min(progress / 10, 200) + 'px'; if (progress < 2000) { window.requestAnimationFrame(step); } } window.requestAnimationFrame(step); // 使用 web worker var w = new Worker('worker.js'); </script> </html> worker.js
var now = performance.now(); while (now + 1000 > performance.now()) { console.log('hello'); } 如果把var w = new Worker('worker.js'); 注释掉,则动画很顺。
先看下动画效果:

上面的图是没有使用 web worker 的,动画很平顺( gif 图看上去卡顿,其实很顺)

而这张图是使用 web worker 处理了一段阻塞代码,会导致动画明显卡顿
问题:Web Worker 明明是开了一个新线程来处理阻塞问题,虽然没有完全阻塞主线程 但确实让动画出现明细卡顿,这是为什么?
1 xrr2016 2019 年 11 月 30 日 实验了下是 `worker.js` 里面的 `console.log('hello');` 这句影响的。 |
3 myqoo 2019 年 11 月 30 日 控制台关了测的吗?开着肯定不行,大量 console.log 会占用 UI 渲染线程的 |