I'm going to use NPM to install a web server, but you can use any web server. NPM install dash g serve. That's an open source server. Because I'm in the Mac, I will request route permission. We are done, so now we can execute serve in the current folder and we have a server that we can control click or command click on the Mac, to see in the browser.
So this is what we are seeing on the browser. If I open developer tools and open the console, if I click console test I can see hi. So pretty simple. But now let's do something in the start button. So going back into the code, I will write the following code. I will say while a counter is less than 50, it's a counter that I'm going to create, start at zero, I'm going to say that counter is equal to counter plus one, but I'm going to use a module of 40.
So in this case, when the counter gets to 40, it will go back to zero. So probably you are thinking, "Hey, that code is wrong." And yeah, it's wrong. Because you will never reach 50 so this is an infinite loop. So let's see this in action. Back in Chrome, I will refresh, I will click a start, and if you pay attention, the border of a start, keeps pressed forever. Now if I click console test, the button, it doesn't work.
So my website is now unresponsive. So we are blocking the thread, the only thread that the browser has. So all the rendering, all the web handling, is happening only in one thread, and we are currently blocking the thread. I can try to close the tab, and even sometimes it's not going to work. And if we go to the menu in Chrome, more tools, task manager, we can see that the tab with the title Threads as we can see now we're tab, is taking the whole CPU.
So it's using the thread, so I can end the process from here if I want. Now let's see what happens in Firefox. I'm here in Firefox. I will do the same, so I will open the console, so console test is working properly. I will hit a start, you can see the button is still pressed, forever. If I hit console test, it doesn't work. And in Firefox, after a while we will see that yellow dialogue saying that the web page is slowing down your browser. What would you like to do? Because we are using too much time of the main thread.
So we can stop it from here. And in this case, the script was terminated.
- Creating dedicated workers
- Creating shared workers
- Creating basic workers
- Sending messages to web workers
- Optimizing app performance with web workers
- Handling web worker errors