JavaScript Async - Basic Worker |
Written by Ian Elliot | |||||
Monday, 17 April 2023 | |||||
Page 4 of 4
Periodic Updates – The Event ProblemThere is nothing stopping you from adding a periodic update to the Worker thread so that the UI thread displays the progress of the calculation. You might think that all you have to do is setup a periodic event using setTimeout or setInterval something like: var state = {}; state.k = 0; state.pi = 0; var i; setInterval(this.postMessage(state),1000); for (i = 0; i < 100000000; i++) { state.k++; state.pi += 4 * Math.pow(-1, state.k + 1) / Notice that the setInterval fires an event every 1000 ms i.e. every second that the UI will process and display the status. If you try it you will discover that it doesn't work. The reason is very obvious once you notice that the Worker thread is fully occupied when the one second events occur and so they remain in the worker's event queue. Notice that it is the Worker thread that processes the worker's event queue. The periodic updates occur all at once when the calculation is over and continue to happen from then on. If the Worker thread is occupied with a computation then it can't service the event queue. This is exactly the same problem we had with the event-driven UI thread and it is the problem with all event-driven threads – they have to be doing nothing to respond to events. We could use the techniques we used to break up the calculation in the UI thread, but this would lose us some of the advantage of using a Worker thread. You might think that the solution is to use yet another Worker thread just to service the regular events, but the problem here is that another Worker thread would not have access to the status object. The simplest solution is to include a timer in the loop that does the calculation and use it to fire the message event: var state = {}; state.k = 0; state.pi = 0; var i; var time=Date.now(); for (i = 0; i < 100000000; i++) { if(Date.now()-time>1000){ this.postMessage(state); time=Date.now(); } state.k++; state.pi += 4 * Math.pow(-1, state.k + 1) / This works, but testing the time every iteration is inefficient. However, attempts to make it more efficient are not easy. In chapter but not in this extract
Summary
Now Available as a Book:JavaScript AsyncYou can buy it from: Amazon Contents
Also by Ian ElliotJust JavaScript: An Idiomatic Approach To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info <ASIN:1871962560> <ASIN:1871962579> <ASIN:1871962528> <ASIN:1871962501> |
|||||
Last Updated ( Wednesday, 19 April 2023 ) |