Ready to watch this entire course?
Become a member and get unlimited access to the entire skills library of over 4,900 courses, including more Developer and personalized recommendations.Start Your Free Trial Now
- View Offline
- Using the Communications API
- Understanding geolocation
- Getting and watching the current position
- Using web workers and WebSockets
- Implementing mobile web user interfaces
- Managing data in a mobile web application
- Working offline
- Using Web SQL
- Using drag-and-drop
Skill Level Intermediate
In this lesson, we're going to see how to do background work in HTML5, by using a Web Worker. This is very handy, if you have some long running task that you need to perform, like a complex calculation. Or if you need to call a webservice that maybe takes ten seconds to come back. You really don't want to do that on the main user interface thread because it would block the user interface. Instead, you can start a BackgroundWorker, like I've got in this example. And in the background, some background work is going to happen while the main user interface remains responsive. So what just happened there? When I clicked that button it created a Web Worker, which posted this message to a background thread. And in the background thread, it spent five seconds being busy and then it posted this response back to the main page.
Now there's no limit on the number of Web Workers you can create from a main page. For example, if you wanted to call five web services that might each take ten seconds, then you can do that concurrently. Create five Web Workers, all of them running at the same time as background threads. So to illustrate, let me click this button several times. I'm going to click it three times, once, twice, three times. I have three BackgroundWorkers running now, three Web Workers, each of them running concurrently. And after five seconds, each of them came back.
So thread number two started at 154113 and it finished at 154118, five seconds later. And thread number three, that one started at 15:41:14 and it finished at 15:41:19. Again, that's five seconds later. So you can have any number of background threads running at the same time. And while they're running, the main user interface is still usable by the user. They can also cancel a BackgroundWorker.
So, for example, if I start the worker here, and before the five seconds elapses, if I click this button, it'll cancel that Web Worker and its finished now. So let's see how this works. First of all, notice that the white page I am using, simpleeco.html, is being run through a web server. On my machine, I have Internet IIS for Microsoft, I've copied these files on to the web publishing folder for IIS, which is inetpubwwroot. So, let me show you simpleecho.html in the editor.
Go back in to the main page here, simpleecho.html, and I'll just skim down to the bottom first, just to show what the basic page looks like. So we have the two buttons, one button that starts a BackgroundWorker, and one button that cancels a BackgroundWorker. A text there, we have the space all the messages come back from the Web Woker. Okay, so when my main web page is loaded, this is the initialization code. We just handle the buttons, and we get the result area. At the top of my script, if I just take it back to the top of the code here, I have declared some global variables.
Most interestingly, I think, is on line 16. Because I want to have multiple Web Workers running concurrently, and I want to be able to track them, then here I've created an array. That array will have a new Web Worker object added to it, every time I click the Start button. So in my example here, every time I click start, it'll create a new Web Worker object, and add it into the array. I want to click cancel. What the Cancel button does, is effectively to cancel the most recently created Web Worker.
Okay? So it doesn't necessarily need to be all in the same folder. So that's my Web Work object. Web Workers have two events that will occur during their lifetime. There's a message event, which will post back data from the background thread when it's finished, like with the result. And there's an error event if anything goes wrong. So typically what you do, once you've created your worker, the next step is to handle those two events. I'm handling the message event, the handle the result data from the BackgroundWorker.
And that'll be passed into a function called On Message, and we'll see that in a moment. And the error event, will be handled by my on-error function here. So, there's my worker object, and I've handled events on it. I push that worker into my array, so that I can cancel them later on, if I want to. And then I post some data into the worker. I actually get the worker to do some work, and this is how you do it. You take your worker object, and you call the post message function.
And the post message function takes a single parameter, which can be any data you want it to be. So in this case, the data is a simple string, and it will say something like hi from worker zero, or hi from worker one. Everytime I click the Start button, it will increment the counter, so we get a different message for each worker. And you might recall that's what we saw, hi from worker one and hi from worker two. Okay. So that's the data that I'm going to be sending into the background thread. And we're going to see what that does with it in a moment. I also display a status message here on the page, just to illustrate that I've sent the data, and the date that I've sent it. Okay.
So, that's what happens when I click that button. When I click the Cancel button, this is the function that gets called: cancel worker. So we get the most recently created worker from the array. And assuming that the array wasn't empty, this is how you can cancel a BackgroundWorker. You call the terminate function on the worker object, and that will completely terminate the background thread immediatley. Okay, so let's assume we haven't cancelled the BackgroundWorker.
The BackgroundWorker, when it's finished will post us back some data and that is handled in my on message function here. So if you remember, I'll just go up a few lines just to remind you what happened. When I click on my work object here, on line 29, I said when that workup posts me data back again, I want to handle the message event. And that's what this function here is. This function we see is an event augment here. This contains data sent back to you from the background thread.
And this prompter here is the data you post in from the main page. So, if I just take you back, to the main page. When I said, post message, the data here would have been something like, hi, from worker zero. Okay, so this prompter here, will have a data string such as, hi from data zero. Okay, so let's take a look what this mesage handler is doing. This will be called, when the user clicks the Start button, it sleeps four or five seconds.
In the BackgroundWorker, it handles that message event. And in the message handler, if it wants to, it can post a message back to the main page when it's finished. And whatever data gets sent in here, e.data.Q here. That data is then picked up in the message handler back in the main page. Okay, so we have this message handler here which picks up that data. There.