Imagine we created a 10 second timer. Every second, the count is outputted to the console.
Now imagine we were required to execute an expensive function while the timer is running.
To mock an expensive function, a
while loop that runs for 3 seconds will be used.
If you start the timer, then start the expensive function, you will notice the output is missing some numbers.
When the counter has started, every second, the engine outputs a number to the console.
When the expensive function is invoked, it starts executing the
When it comes time to output the next number, the engine can't do it.
It needs to 1st complete the
while loop before it can continue with the counting.
A solution to this problem is to move the expensive function to a different thread using a worker:
- 1. Create a worker containing the function,
- 2. Send a message to the worker when the function need to be invoked,
- 3. Have the worker execute the function &
- 4. When complete, have the worker send back the results of the function.
Now the count is no longer blocked when the expensive function is executed.
A Web Worker can also be used within a React Component via the