-
Notifications
You must be signed in to change notification settings - Fork 5
/
withWorkers.html
48 lines (39 loc) · 1.25 KB
/
withWorkers.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>worker demo</title>
</head>
<body>
<div>
<h1>使用workder:</h1>
<p>点击开始计算按钮,系统开始通过workers计算斐波那契数列。</p>
<p>在使用workers的情况下,可以看到计算过程中,浏览器的UI线程不会卡住。</p>
</div>
<button style="padding: 10px; margin: 10px 0;">开始计算</button>
<div>
<span>当前时间戳:</span>
<span class="time"></span>
</div>
<script>
//
let button = document.querySelector('button');
let worker = new Worker('workers.js');
let time;
button.addEventListener('click', function () {
time = new Date();
worker.postMessage('start');
});
worker.onmessage = function (messageEvent) {
alert('计算结束,结果为' + messageEvent.data + ',用时' + (new Date() - time) + 'ms');
}
// 计时器
let timeDom = document.querySelector('.time');
function updateTime() {
timeDom.innerHTML = +new Date();
requestAnimationFrame(updateTime);
}
requestAnimationFrame(updateTime);
</script>
</body>
</html>