-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex2.html
51 lines (44 loc) · 1.62 KB
/
index2.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
49
50
51
<!DOCTYPE html>
<html>
<body>
<h1>Web Worker Example</h1>
<input id="workerInput" type="text" value="heyyy">
<script>
var myWorker = new Worker('worker.js');
var isWorkerBusy = false;
var latestValue = null;
var lastPostedValue = null;
// Event listener for input changes
document.querySelector('input').addEventListener('input', function() {
var inputValue = this.value;
latestValue = inputValue;
console.log(inputValue);
if (!isWorkerBusy) {
isWorkerBusy = true;
lastPostedValue = inputValue;
myWorker.postMessage(inputValue);
}
});
myWorker.onmessage = e => {
console.log('Message received from worker', e.data);
document.querySelector('h1').textContent = e.data;
// The worker has finished processing, it's not busy anymore
isWorkerBusy = false;
// If the latest value has changed since we last posted to the worker,
// post the latest value to the worker.
if (lastPostedValue !== latestValue) {
isWorkerBusy = true;
lastPostedValue = latestValue;
myWorker.postMessage(latestValue);
}
};
// Posting the initial value to the worker
var inputValue = document.querySelector('input').value;
latestValue = inputValue;
lastPostedValue = inputValue;
console.log(inputValue);
myWorker.postMessage(inputValue);
isWorkerBusy = true;
</script>
</body>
</html>