Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Getting started with web workers

From: HTML5 Power Workshop

Video: Getting started with web workers

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.

Getting started with web workers

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.

Here it is, simpleecho.html. As you can see, I've copied it into the inet pub, wwwrootnet folder. It's also in your project files folder, if you want to explore. There's also another file involved. The Javascript file here, is the place where the background work happens. This is the way Web Workers work. In order to perform work in a background thread, you have to put that work into a Javascript file, and then run it from the main page. So let's look at the details.

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.

In this case it's like popping it off a stack. And in fact that's exactly what it does in the code. So let's go back into the code. That's my array, which will hold Web Workers. And on line 21, this is the function that will be called when I want to start new Web Worker. So let's have a look at the details in here. First of all, this is how you can test whether your browser supports Web Workers. JavaScript should have a worker object. If that worker object is undefined, then it means your browser doesn't support Web Workers.

In that case, you can't do multi threading, so you'd have to come up with an alternative plan in that case. On the other hand if we do support Web Workers, then this is how you can create a Web Worker and get it to do some work. You create a new worker object, and you specify the name of the JavaScript file that contains the code you want to run in the background thread. So in this case, it's just a simple JavaScript file name. But in reality, it could be a domain name, an HTTP colon backslash, whatever.

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.

If you like, it's the result from the background thread. And this is how you access the data. You take the event object, and you say .data, okay? So that would be the response that came back from the background thread. So in the example, it was the uppercase version of the string that was passed in. And that's displayed in the text area on the screen. Okay, one other thing to think about in the main page, errors can happen. So for example, when you try to load the JavaScript file, may be it can't be located or may be there is a syntax error or some other kind of problem in the JavaScript file.

So you really must handle the error event, and this is not but shows how to do it. The own error handler has an event argument, it has three bits of information that's useful. It'll tell you the file name, of course, the error, so that could be http colon and the name of your JavaScript file. It'll tell you the line number with the error code, and the message describing what's the problem. Syntax error for example. Okay. So that's the main page. Let me just recap a few things before we look at how the BackgroundWorker actually does the work.

So, when I created my workable object, I set up some event handlers on it, and then I said post message to send some data to that BackgroundWorker. Now, the BackgroundWorker knows which file it's talking about, so that file will be loaded asynchronously into the browser. And when you post a message to it, this is how the background worker handles it. BackgroundWorker page, the Javascript file, in other words, has to handle the message event. And whatever code you put into that function, is effectively the code that will run in 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.

I have a function up here which is deliberately inefficient, and it sleeps for five seconds. After those five seconds have elapsed, then this is how you can return results back to the main page. You call post message again, and you specify the data that you want to be turned back. This is the result of the backround thread. So, that's the end of this example. I'll just summarized the key points. JavaScript and HTML 5, we have a worker object. When you create a worker object, you give it the name of the JavaScript file that you'd like to run. You handle the message event, and the error event, and then you post message to actually get the BackgroundWorker to do something.

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.

Show transcript

This video is part of

Image for HTML5 Power Workshop
HTML5 Power Workshop

22 video lessons · 4632 viewers

Andy Olsen
Author

 

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold
Share a link to this course

What are exercise files?

Exercise files are the same files the author uses in the course. Save time by downloading the author's files instead of setting up your own files, and learn by following along with the instructor.

Can I take this course without the exercise files?

Yes! If you decide you would like the exercise files later, you can upgrade to a premium account any time.

Become a member Download sample files See plans and pricing

Please wait... please wait ...
Upgrade to get access to exercise files.

Exercise files video

How to use exercise files.

Learn by watching, listening, and doing, Exercise files are the same files the author uses in the course, so you can download them and follow along Premium memberships include access to all exercise files in the library.


Exercise files

Exercise files video

How to use exercise files.

For additional information on downloading and using exercise files, watch our instructional video or read the instructions in the FAQ .

This course includes free exercise files, so you can practice while you watch the course. To access all the exercise files in our library, become a Premium Member.

Join now Already a member? Log in

Are you sure you want to mark all the videos in this course as unwatched?

This will not affect your course history, your reports, or your certificates of completion for this course.


Mark all as unwatched Cancel

Congratulations

You have completed HTML5 Power Workshop.

Return to your organization's learning portal to continue training, or close this page.


OK
Become a member to add this course to a playlist

Join today and get unlimited access to the entire library of video courses—and create as many playlists as you like.

Get started

Already a member ?

Become a member to like this course.

Join today and get unlimited access to the entire library of video courses.

Get started

Already a member?

Exercise files

Learn by watching, listening, and doing! Exercise files are the same files the author uses in the course, so you can download them and follow along. Exercise files are available with all Premium memberships. Learn more

Get started

Already a Premium member?

Exercise files video

How to use exercise files.

Ask a question

Thanks for contacting us.
You’ll hear from our Customer Service team within 24 hours.

Please enter the text shown below:

The classic layout automatically defaults to the latest Flash Player.

To choose a different player, hold the cursor over your name at the top right of any lynda.com page and choose Site preferences from the dropdown menu.

Continue to classic layout Stay on new layout
Exercise files

Access exercise files from a button right under the course name.

Mark videos as unwatched

Remove icons showing you already watched videos if you want to start over.

Control your viewing experience

Make the video wide, narrow, full-screen, or pop the player out of the page into its own window.

Interactive transcripts

Click on text in the transcript to jump to that spot in the video. As the video plays, the relevant spot in the transcript will be highlighted.

Learn more, save more. Upgrade today!

Get our Annual Premium Membership at our best savings yet.

Upgrade to our Annual Premium Membership today and get even more value from your lynda.com subscription:

“In a way, I feel like you are rooting for me. Like you are really invested in my experience, and want me to get as much out of these courses as possible this is the best place to start on your journey to learning new material.”— Nadine H.

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.