I want to let Javascript
run two operations at the same time.
I want to let javascript process a large loop
while running interval
to do a timer.
I searched online and found that we only have two ways either using a event loop or using a web worker.
I have been struggled with it for a long time, but it is pretty for me to understand how to really use web worker
or event loop
.
For the event loop
, I can't really understand the code the documentation it gives:
while (queue.waitForMessage()) {
queue.processNextMessage()
}
What does the queue
stand for? If I directly use queue
in my code, it will display queue is not defined
Also, how could i use it actually it my code?
For the web worker
, here is my code:
let result = document.getElementById('result')
let time = document.getElementById('time')
let worker;
let script = document.getElementsByTagName('script')
let interval = setInterval(function(){
time.textContent = parseFloat(time.textContent)+1
},1000)
function display(){
for(let i =0;i<10000;i++){
result.innerHTML +=i
}
}
let startworker = function(){
if(typeof(worker)=='undefined'){
worker = new Worker(script);
//I think this will produce error, but I don't know how to deal with the onmessage to let it run the function
worker.onmessage = function(){
display();
}
}
}
<div id='result'></div>
<button onclick='startworker()'>Click</button>
<div id='time'>0</div>
button
, it will produce failed to construct 'Worker'
. Also, for the onmessage
part, I don't really have idea of how could I make it run the loop
and I think my code is incorrect.
I have read a lot of articles and documentations, but I still don't have idea of how to do that.
Could anyone helps me to understand those two ways and give me a better way of solving this situation?
Thanks for any responds and forgive my ignorance!!!
The example:
let result = document.getElementById('result')
let time = document.getElementById('time')
let interval;
function start(){
interval = setInterval(function(){
time.textContent = parseFloat(time.textContent)+1
},1000)
setTimeout(reallystart(),0)
}
function reallystart(){
for(let i =0;i<10000;i++){
if(i == 9999){
window.clearInterval(interval)
}
result.innerHTML +=i
}
}
<button onclick='start()'>Click</button>
<div id='result'></div>
<div id='time'>0</div>