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

Communication patterns

From: HTML5 Power Workshop

Video: Communication patterns

In this lesson, we're going to look at various communication mechanisms and other techniques that are useful when you are using Web Workers in a real situation. So, I just run this sample application first and as I am going through it I will describe various patterns that we are using. So, the Web page is called Primenumberapp.html and I've copied it into my Web Publishing folder. And the idea of the example is you can get the Background Worker to tell you all the prime numbers in a certain range. So, in the first text box, I can type a lower number, such as 100, and then an upper number, well, let's give it a big number, 80,000.

Communication patterns

In this lesson, we're going to look at various communication mechanisms and other techniques that are useful when you are using Web Workers in a real situation. So, I just run this sample application first and as I am going through it I will describe various patterns that we are using. So, the Web page is called Primenumberapp.html and I've copied it into my Web Publishing folder. And the idea of the example is you can get the Background Worker to tell you all the prime numbers in a certain range. So, in the first text box, I can type a lower number, such as 100, and then an upper number, well, let's give it a big number, 80,000.

So, it's going to take a while to take all those prime numbers. Well let's click Find Primes, when its found all the prime numbers in that range. It'll send me back a result message and the result message will indicate while the start time and the end time of the Background Worker. And it'll also indicate obviously all the prime numbers that its found during that time. So, that's the result message, if you like. Another message that might be useful to send back from the Background Worker might be an error message if something goes wrong.

In my example here, I've coded it so that if the upper number is actually less than the lower number, then effectively, it'll throw back another message to say Error. So if I click Find Primes again. You can see here, I've retrieved a different kind of message back this time. To say there's an error. The lower number is higher than the upper number. That shouldn't be the case. So, that's the second kind of message we need to indicate error conditions. Now, it's an important point to bear in mind but if something goes wrong in the background worker, don't throw an exception.

The only way we communicate from the Background Worker back to the main page is by calling Post Message. And it's up to you as a developer to decide how to differentiate between normal messages. Such as here's the data, as compared to error messages, like this one. Now, a third category of message that I often find quite useful. Is to pass back diagnostic messages from the Background Worker, to say well, this is what I've done so far. Now, if I show you this example, I just refer back to the original numbers, primes like so.

Between 100 and 80 thousand. What actually happens in the code in the Background Worker, everytime it finds another prime number. Every single prime number that it finds, it posts a single message back to the main page to say right here is another prime number. So, each one of these prime numbers would correspond to a separate post message in my example, to illustrate, well this is what I've got so far. Now, in the main page, I've set up a handler for that. And what it does it displays those messages, those diagnostic messages, in the Console window. The way you get the Console window depends on what type of browser you're using.

In Chrome, you can get it via Developer tools, Internet Explorer and Firefox Firebug have similar mechanisms. In Chrome, the way you see the console is by pressing F12 to bring up the Developers tools window. And then if you click on the Console tab here, it displays the console. These are all the messages that the main page has logged to the console during execution. So, if I just clear the console first of all, and then I'll try it again.

I'll give it a smaller range this time so it doesn't take so long. These are all the diagnostic messages that were posted back, from the Background Worker, picked up by the main page, and the main page logs them on the Console. This is a very useful mechanism, because when you're right then the Background Worker in the JavaScript file. How do you know if something's gone wrong? Maybe you've got a syntax error, or maybe something's incorrect in your logic. In a normal application, in a normal JavaScript file, you might put some alert statements, or you might put a break point.

We can't do that when it's running in the Background Worker. You can't set break points, and you haven't got access to the alert function either. Because the Background Worker doesn't have any access to the document object for the main page. It's a fundamental limitation so the mechanism I find most useful is for the Background Worker to post back a message to the main page. To say here's information that I would normally display in an alert box, this information. Can you please do something with it, so the user knows what we've got? And that's what happens here. Console, log, messages, like so.

Right, I think it's time to look at the code. So, I've got Komodo Edit open, and there are actually three files involved, not two. I'll explain why the third file is useful in a moment. All of these files are in your Project Files folder. I've copied them into my Publishing folder for the web, inetpubwwroot. So, what we'll do is we'll first of all take a look at the prime number app.html. Because in there, it illustrates how you can pass and retrieve different kinds of message. Right, so I'm going to scroll down to the bottom of the page, just to discuss the overall layout of the web page itself. So, text boxes for the user to enter the lower number and to enter the upper number.

And then buttons to allow the user to start and to stop the Background Worker. A message area, which is actually displayed in blue because of some styling. And then a text area where all the results for the prime numbers will be displayed. Okay, so that's fairly straightforward. And then, when the page is loaded, I have some code here that just handles the buttons. And sets up some global variables to access those text boxes and the text area. Now, let's take a look at the Start button.

When the Start button is clicked, this function is invoked, FindPrimes. So, we create a new Worker object, and it's going to run a JavaScript file called getprimenumbers.js. And we'll take a look at that in a moment. And then as usual, it handles the message and the error events. And it posts a message to the Background Worker specifying the lower number, the upper number and the date when this Background Worker was started. Obviously, when we run the example, when it's finished, it'll confirm the start time and the end time to show how long it took.

Okay, so that's fair enough. At that point I'm going to go into the JavaScript file to see how it handles that message is passed in with the lower number the upper number and start time. So, lets take a look at getprimenumbers.js. Now, the first thing you'll notice, and this is really just an aside, but I thought it was useful to talk about it. Sometimes, your Background Worker JavaScript file might want to import other script files maybe your using jQuery or something like that. The way to do it from the Background Worker file is by using the Import Scripts function.

Normally, you'd use a Script Tag, and you'd reference the name of the file you want to import. You can't do that in the Background Worker, because you don't have access to the document object to load the script. You've gotta call this function like so if you want to pull in some other script files in your Background Worker file. Okay, so that's an important point to bear in mind. Incidentally, Utilities.js is here, and it's just got a simple function really, just for illustration purposes. You give it a number, like 100, and it'll return true or false, depending on whether or not it's a prime number. So, you can have a look at that code yourself when you get a moment. I could have implemented this much more efficiently, but of course, part of the purpose in this demo is to deliberately be slow. So, you get a chance to actually see things happening during the demo. But anyway, that function, you give it a number, and it returns either true of false to tell you whether that particular number is a prime number of not. So, let's go back into the main JavaScript file and I'll scroll down to the bottom just to show this statement on Line 44. It handles incoming messages from the main page. And every message that arrives is handled by our Message Handler function, which is here.

In the Message Handler function, I retrieved the various bits of information passed in on the main page. So, the lower number, like a hundred, and the upper number, like 80,000, and the start time. Now, the key point here is, if you look at this function, I have three different types of post message function going on. On Line 13, I post a message to indicate a diagnostic message if you like, or a debug. Now, normally in a real JavaScript file if you like, I would display an alert here to say oh, this is where I got to. I'd like to just pop up this message on the screen to tell viewers what's happening.

We can't do that because we don't have access to the Document Alert function. The only way to get information back to the user is by post message. It is the only way you can do it. So, that post message is going to post back diagnostic information. What I've done is, in my object that I pass back, whenever I post the message back to the main page. In my strategy here, I always set a property called Type, and the type is a flag, basically, to say what kind of message and I sending. If the type is debug, then the browser will display it in the Console.

And the message will be that this low number. In that order of number and that start time this in fact to be the start of the worker to determine the prime numbers in that range, Okay. So, that's what happens if I set the type to be debug. Before we finish this demo, I'll also take you back into the main page to show how the main page differentiates between these different types of post back. So anyway, this will send back a diagnostic message to say, I am here, effectively.

The second post message is on lines 18 and 19 and this effectively is the equivalent of exception handling. Don't throw an exception. That's not the way to do it. If you want to convey error information back to the main, post a message. And set some sort of flag to say, well this is an error message, as opposed to a normal message. So, I post message, and this time, I decide to set the type flag to be Problem. You can use any mechanism you want here. You could set an integer to be 12345, but somehow, the main page has to know this isn't like a normal message, this is a problem message. And in that case, the message I sent out is this error message here, effectively. That would be equivalent in normal programming to throwing an exception with that error message as the parameter.

But when we're using Background Workers, you have to post it as a message instead of throwing it as an exception. So, we can either post the message with diagnostic information with type equals debug. Or we could set post message with problem information and I have set type equal to problem here. I have closed that mechanism and then finally probably most easily to understand have a look at this. This bit here will loop through all the numbers in the range, and it'll use that Helper function that I looked at about five minutes ago.

And if the number is prime, it pushes it onto an array. That's going to be my full set of prime numbers when we're finished. And then it posts a message here to say, this is how far I've got so far. This is another diagnostic message really, similar to the one we had way up here. And this one says, oh, I've just found another prime number, would you believe it? And the prime number is N. So, prime number 101, for example. So, that's going to happen every time we go on that loop, it's going to do post message. Every time it finds a prime number. And it'll be a type equals debug.

And that's going to logged in the console. Finally, after it's gone through all the numbers, and it's accumulated the full set of primes. Then finally, we're ready to send back the complete set of data. And that once, of course, type equals result. And that will indicate when the thing started, the current time when that will get ended and all the prime numbers that I've managed to find. So, we've almost done here. Let's just take a final look at prime number app.html to see what it does with all those different kinds of message that come in. So, you might now what to expect here.

This is the All Message function and it's just basically an If statement to say what kind of message have I just received. It takes the type flag which is a bit like a discriminator effectively and it says. Well, if you've sent me a debug message, then I'll get the message that you've sent me and I'll log it to the console. So, those were the messages that we saw coming up down here. On the other hand, if the message type is problem, then it displays the arrow message in here, and that's what happened when I type in something like this. Problem occurred, lower number is higher than upper number. And finally, if the data type is result, then it displays a message confirming the result.

And then displays all the prime numbers in the text box. It's a very useful mechanism, very powerful. And I think the key thing to remember is that really it comes down to one simple way to communicate back from the Backward Worker to the main thread. You have to use the post message function and then define some sort of mechanism. That allows the main page to decide how to interpret the incoming data.

Show transcript

This video is part of

Image for HTML5 Power Workshop
HTML5 Power Workshop

22 video lessons · 4046 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 preferencesfrom 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.

Are you sure you want to delete this note?

No

Your file was successfully uploaded.

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.