JavaScript Function Throttling

JavaScript

JavaScript LogoWhen an event such as window.resize() runs more often than you want it to, you can control how many times your event handler runs.

Sometimes events fire very quickly and more often than you would like; window.resize is a perfect example. It’s quite common to assign an event handler that will run every time the user resizes the browser. Unfortunately, however, there is no “resize-end” event. The resize event will fire for every change in pixel. This means that if the user resizes the window 100px, that resize event will run 100 times. But what you usually want is for that event handler to run when the user has finished resizing the window. Since there is no “resize-end” event, we have to use a timeout to imitate the kind of behavior we want.

Example # 1

In Example # 1, we have assigned an anonymous function to the onresize event of the window object. Unfortunately, though, the unordered list is updated every time the window size changes by one pixel. What we want is for the update message to appear after the user has finished resizing the window.

Click here to see the code for Example # 1 in action: http://jsfiddle.net/zWQ8D/

Example # 2

Click here to see the code for Example # 2 in action: http://jsfiddle.net/zWQ8D/1/

In Example # 2, we have created a function named “throttle”. This function will set a timeout of whatever numeric value is passed in as an argument. But every time that same function is called, the timeout, which exists in the global scope, is cleared and reset. Because our window.onresize event calls this function many times in rapid succession, the timeout is constantly re-set, which means that the function passed-in never executes.

The magic happens after the user has stopped resizing the window. Since every call to the “throttle” function sets a timeout, once 250 milliseconds has passed since the last call to the function, the final timeout actually executes. The net result is that the event handler for the window.resize event “feels” as if it only executes once the user has finished resizing the window. What actually happens is that the event handler is passed to the “throttle” function over and over in rapid succession, but our “throttle” function ensures that it only executes if 250 milliseconds has passed since the last time it was called.

Making JSONP Calls from HTML5 Web Workers

HTML5

HTML5 LogoThe importScripts() function can be used to load any JavaScript file asynchronously from within a Web Worker, making JSONP a snap.

I just put the finishing touches on a photo gallery for a fairly large commercial web site. This template involved two dependencies: mustache.js and a jQuery carousel plugin, as well as three JSONP calls. All of this has to happen before anything can be displayed in the browser. Fun stuff.

I’ve spent plenty of time pressing F5 over and over to see how many milliseconds I could shave off the page load time. Since there is a bit of data crunching that also has to happen once all dependencies and JSONP calls have loaded, I started to think that this project would be a perfect candidate for some Web Worker love (of course with a safety net for older browsers). After some A/B testing, I could see that there was no real savings when implementing Web Workers. This is because the average 3-second load time was mostly due to the multiple asynchronous calls, not the data crunching. Since asynchronous calls are asynchronous, they don’t lock-up the browser, and it is only their latency that “keeps us waiting.”

That said, in the process of setting up my A/B testing, I had fun messing with Web Workers, and picked up a few new tricks, so I thought I’d post an article about making JSONP calls from a Web Worker.

If you’re not too familiar with HTML5 Web Workers, you might want to read these three posts; they offer an overview and a quick dive in to the topic:

Getting Started with HTML5 Web Workers – Part I
Getting Started with HTML5 Web Workers – Part II
Getting Started with HTML5 Web Workers – Part III

Before diving into the Web Worker code, I’ll just mention that the JSONP call we make responds pretty quickly, almost too quickly. As a result, it’s tough to demo our Web Worker, because there is no sense of “wait” (I spent over an hour making a pretty “loading” experience that merely flickers for a nanosecond because the JSONP call returns so quickly : – ). So I’ve implemented a “sleep” feature: we add &sleep=NUMBER to the query string. This way, we can make the JSONP call perform a little slowly, which helps to demonstrate our topic. Here is the PHP code that is added to the top of the JSONP file:

Ok, a little JSONP / Web Worker Action Please!

Example # 1

In Example # 1, we have the code for our Web Worker. First, there is the JSONP callback. In this callback, we fire off a message to the script that started the worker, and pass it the JSON data. Note that we need to use JSON.stringify() to convert that JSON data to a string. This is because we can only pass strings as messages to and from a Web Worker. But if we “stringify” a JSON object, that will do just fine.

Next we have set up an event listener. When the calling script sends a message to this Worker, the code inside of the event listener is executed. We create a random integer which is used to tell the JSON page to “sleep” for a few seconds, imitating a slow response. The other random # is used as a cache buster.

After that, we simply make the JSONP call. The importScripts() is oh-so-lovely and makes it super easy to import any JavaScript file.

Example # 2

In Example # 2, we have a simplified version of the click handler for the “Make JSONP Call” button. It simply sends a message to the Worker, which “starts” it.

Example # 3

In Example # 3, we instantiate the Worker() constructor, and then set up the event listener for that Worker. The code inside of this event listener will be executed when the Worker sends this script a message. I won’t drive you nuts by going through it line-by-line, but on a high level, we take the JSON data that the Worker sends us, and use JSON.parse() to turn it back into an object. Then, leveraging Mustache.js, we create an unordered list, using the JSON data that the Worker fetched for us.

Here is a link to the full working example for this article. Make sure you click the “Make JSONP Call” button: http://examples.kevinchisholm.com/javascript/web-workers/jsonp/

Summary

Again, the very act of making an asynchronous script call is not so strenuous for the browser. But I can imagine a case in which you need to fetch some JSON and then crunch the return data before passing it to the calling script. In such a case, the “crunching” is what could bog down the browser. And since data you pass to a Web Worker is essentially “copied,” your script could wind up using more memory than necessary, by getting the JSON data, passing a copy of it to the Web Worker, and then getting a copy back from the Worker once it has finished doing some work on the data. That is three copies of the same chunk of data!

By initiating your JSONP call from the Web Worker, you get the data, crunch the data, and then pass the data to the calling script. This removes one “copy” from the whole scenario. And, I’m thinking that after sending the data from the Worker to the calling script, you could probably delete the data inside of the Worker, freeing-memory. Although it will probably get cleaned up by garbage collection. More fun stuff to investigate.

Happy Web Worker-ing!

Kevin

Helpful Links for Web Workers

http://www.sitepoint.com/javascript-threading-html5-web-workers/

http://www.storminthecastle.com/2013/04/19/make-your-ui-more-responsive-with-html5-web-workers/

http://www.codediesel.com/javascript/introducing-html5-web-workers/

http://refcardz.dzone.com/refcardz/html5-web-workers

http://www.tutorialspoint.com/html5/html5_web_workers.htm

Problems Making JSONP Calls in JSFiddle – PROBLEM SOLVED

JavaScript

JS Fiddle LogoAll the JavaScript you write in the JSFiddle “JavaScript” box gets wrapped in an anonymous function and assigned to the window.onload event of an iframe that is shown when you click the “Run” button.

Last week I published this post: Problems Making JSONP Calls in JSFiddle 

As I was testing out some code, I noticed that JSONP calls were failing when using JsFiddle.net. I took a look at it and just found the answer. It wasn’t too big a deal, just needed to understand how JsFiddle executes the JavaScript code that you put in the lower-left-hand box (i.e. the “JavaScript” box).

Here is the code I testing, that was failing:

In this code, I use the “var” keyword to declare “myCallback” as a function expression, just like I was told in JavaScript summer camp back in the 70s. But even when using the “var” keyword, any variable declared in the global scope becomes a property of the window object. Anyhooo, I confidently assumed that my variable “myCallback” (or window.myCallback) would be available to the script that is loaded by the JSONP call. But that code failed and the following message appeared in the console: “myCallback is not defined”. Bummer.

Well, after a few minutes poking around in Google Chrome Web Inspector, I found the issue:

As I had suspected, JsFiddle executes your JavaScript code in an iframe. What I did not realize at first, is that it wraps all of that code in an anonymous function, that is assigned to the window.onload event. So by using the “var” keyword, my “myCallback” variable became private to the anonymous function. Here is the code that is actually executed by JsFiddle when I clicked “run”:

As a result, my “myCallback” variable (i.e. the function expression) is private, and not available to the outside world.

The answer was simple. I just had to force my “myCallback” variable to be global by removing the “var” keyword:

 

This forces “myCallback” to be an implied global, which in-fact becomes a property of the window object. It’s the exact same thing as if I had written: “window.myCallback – function()….”

Here is the JsFiddle.net link for the code that fails: http://jsfiddle.net/DQHax/

Here is the JsFiddle.net link for the fixed code: http://jsfiddle.net/DQHax/1/

Same thing, only let’s avoid implied globals, and explicitly attach “myCallback” to the window object: http://jsfiddle.net/DQHax/2/

Again, no big deal. But if you found yourself pulling your hair out and were googling for an answer, hopefully I saved you a few strands of hair.

: – )

Kevin

 

 

 

Problems Making JSONP Calls in JSFiddle

JSON

JSFiddle Logo
If you are pulling your hair out while trying to demo a JSONP call with JSFiddle, don’t bother. It won’t work out of the box.

There is no doubt that JSFiddle is a super-useful tool for saving little demos that you can share with others.  I use it like crazy when providing simple demos in this blog. Tons of cool features and in general, a brilliant idea.

One little quirk I ran into this morning is JSONP calls. I’m writing Part II of a post called: “Complex Multiple Script Loading Using the jQuery.when() Method and the jQuery.Deferred Object”. In this second part, I introduce the tricky scenario of adding a JSONP call as a dependency, which is in addition to other dependencies that are multiple asynchronous  JavaScript calls that may (or may not) have already loaded in the page (I know, I know….. I need to get a life).

Anyhooooo….

When attempting the code in example # 1, I got the following error: “myCallback is not defined”.

Example # 1

My guess is that JSFiddle uses iframes to render your test code. I’ve not made any attempt to look into this further, and I’m sure the answer is likely a call to “parent” or something similar. But just in you are pulling your hair out trying to demo a JSONP call using JSFiddle, hopefully this will save you the 20 minutes of troubleshooting that I just did. It won’t work out of the box (again, probably due to the use of iFrames). When I figure out the answer, I will post it. I’ll try to look into it this weekend.

Kevin

Using the jQuery Promise Interface to Avoid the AJAX Pyramid of Doom

jQuery

jQuery LogoNested success callbacks are messy business. The jQuery Promise interface provides a simple and elegant solution.

So, you have to make an AJAX call, and then do something with the return data. No problem, right? Right. What if you have to make two AJAX calls, and then do something with the return data for each one? No problem, right? Right. What if the second AJAX call depends on the success of the first AJAX call?

“…um, well…. then, well… wait a minute… ok, I’ve got it:

I’ll make the first AJAX call…and then inside the success callback function, cache the data somewhere… um… in a global variable for now I guess… yeah, no one will notice. OK, and then inside of that success callback, we’ll nest another AJAX call, and then inside of the second AJAX calls’ success callback, we’ll get our first chunk of data from the global variable, and then, and then… um…and then…”

…yikes!

Obviously, the preceding diatribe was a little over the top, but c’mon…. haven’t you at least once stood at the edge of that cliff and looked over? Fortunately, jQuery features a way out of this mess that is safe, reliable and packed with vitamins.

The jqXHR object

Since version 1.5.1, jqXHR objects returned by $.ajax() implement a “Promise” interface. In short, this means that a number of methods that are exposed provide powerful abstraction for handling multiple asynchronous tasks.

I think it is important to note that the subject of the jQuery Deferred and Promise Objects is deep. It is not an easy topic to jump into and a detailed discussion of this is outside of the scope of this article. What I hope to accomplish here is to provide a simple and fast introduction to the topic, by using a real-world problem / solution.

There are certainly multiple scenarios in which the jQuery Deferred and Promise objects can be useful. I have chosen to use AJAX calls for this, since it is an example of asynchronous behavior that I think most folks can relate to. In order to dramatize the effect of an asynchronous AJAX call, I am using a PHP file that can return a delayed response. Here is the code for the server page:

OK, now some AJAX.

(Note: I highly recommend that you open up the “network”  panel in Firebug or WebKit developer tools so that you can see these AJAX calls in action when viewing the working examples… especially AJAX call # 1, which will take 5 seconds to complete)

Example # 1

In Example # 1 we have a fairly straightforward setup: Two buttons, each resulting in an AJAX call. Notice that the 1st AJAX call takes 5 seconds to complete. Instead of providing an inline anonymous function for the success callback of each AJAX call, we have a generic handler named “success”.

Here is a link to the working code for Example # 1: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-1.html

But what if we want AJAX call # 2 to depend on AJAX call # 1? That is, we don’t want AJAX call # 2 to even be possible until AJAX call # 1 has completed successfully.

Example # 2

In Example # 2, we have a pattern that is known as the “Pyramid of Doom”. This might work for the short term, but it is impractical, not at all flexible, and just plain messy. What if there was a third button, and a fourth button… I think you see what I’m getting at here.

Example # 3

Ahhh… that’s much better!

In Example # 3, we have taken advantage of the Promise interface that is exposed as part of the jqXHR object. If you are wondering what the jqXHR object is, it is the return value of any $.ajax() call. So, while you can simply do this: $.ajax(URL,CALLBACK), the call itself returns a value. That return value is the jqXHR object, which is a superset of the XMLHTTPRequest object.

The return value of $.ajax() is the jqXHR object, which is a superset of the XMLHTTPRequest object, and packed with some powerful features.

We don’t have to dive too deeply into the good ol’ XMLHTTPRequest object (although it is important to know what it is and the critical role that it plays in AJAX). But the key point here is that the jqXHR object wraps the XMLHTTPRequest object, providing some useful features. One of those features is the “Promise” interface.

“….ok, ok Kevin, you’re givin’ me a migraine… where are you going with all this?”

Hang in there; we are at the 99 yard line here. What this all means is that instead of just making an AJAX call, you can assign that AJAX call to a variable. Since the $.ajax() method returns the jqXHR object, your variable is now a Swiss Army knife of AJAXian goodness. You can then implement methods of your object (i.e. your variable). Two of those methods are: .when() and .done();

So, in Example # 3, when we fired the first AJAX call, we assigned its return value to the variable “aj1”. Notice that we did NOT make a success handler call. We simply make the AJAX call, and that call’s return value is held by the variable “aj1”. Then when the user clicks the second button. we set the return value of the second AJAX call to the variable: “aj2”. Now we have two variables and each is a jqXHR object. These are powerful little objects!

The line where the fun really starts is: $.when(aj1,aj2).done()

Notice how the .done() function takes a callback. The callback is fired when the two arguments passed to the .when() method are resolved. And guess what those two arguments are… our two little jqXHR objects!

So, the .done() method knows how to get ahold of the data returned by each of those calls. Now we simply call our generic success handler, passing in the return data of each AJAX call (i.e. each jqXHR object). You may be wondering why I pass in the values “a[0]” and “b[0]”. This is because “a” and “b” are jqXHR objects. It just so happens that the first property of these objects (i.e. the property with the index of 0) happens to be the “responseText” property of that object (i.e. the text sent back from the server).

Phew!

I know that was a lot. But there is much to shout about when it comes to the jQuery Promise interface. As I mentioned, it is a big topic and not easily summarized. But my hope is that these examples will have put a little context around the subject, and will help you to dive in and get started.

Below is the source code for this article’s full working example:

Example # 4:

Here is a link to this article’s full working example: http://examples.kevinchisholm.com/jquery/promise/promise-and-ajax-beginner/example-2.html

Summary

In this article we learned about the jQuery Promise interface. We discovered that since version 1.5.1, calls to $.ajax() return a jqXHR object, which implements the Promise interface. We utilized the .when() and .done() methods of this interface to execute callback functions for two asynchronous tasks. This eliminates the need for nested success callback functions.

Helpful Links for the jQuery Deferred, jQuery Promise and jqXHR Objects

jQuery Deferred

http://api.jquery.com/category/deferred-object/

http://api.jquery.com/jQuery.Deferred/

jQuery Promise

http://api.jquery.com/promise/

http://api.jquery.com/deferred.promise/

http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

jQuery jqXHR

http://api.jquery.com/Types/#jqXHR

http://api.jquery.com/jQuery.ajax/#jqXHR

What’s the Difference Between jQuery().each() and jQuery.each() ?

jQuery

jQuery LogojQuery’s two .each() methods are similar in nature, but differ in level of functionality

Some may find it difficult to understand the difference between jQuery.each() and jQuery().each(). Perhaps the easiest way to understand the difference is to start with jQuery().each(). This method can only be used against a jQuery collection. So when you do this: jQuery(‘#someDiv p’).each(), what you are saying is: “for EACH paragraph that is inside of the element with the ID of “someDiv”, I want to do something. That’s it.

The jQuery.each() method is a static method of the jQuery object. This means that it is just a method that’s out there for you to use, and you need to give it a little more info. But there is a bigger payoff with this method: it can be used to iterate over different kinds of things, not just a jQuery collection.

The syntax for the jQuery.each() method is also simple:

So, OBJECT can be an object, an array, an array-like object or even a jQuery collection. How cool is that? The CALLBACK is a function that will be run against each element in the first argument. The super-star feature here is that the first argument can be a jQuery DOM collection. This means that jQuery.each() can do ANYTHING that jQuery().each() can do. Let’s jump into some code:

jQuery().each()

Example # 1.A

In Example # 1.A, we have an unordered list, with the days of the week as list items. The last two have the “weekend” class applied. We use the $().each() method twice. In the first run, it will iterate over every one of the list items. In the second run, the jQuery collection contains only the last two list items because they have the “weekend” class.

In both cases though, we can see how the $().each() method does one thing and does it well: it iterates over a jQuery collection. Inside of that collection, we use $(this) to get a reference to the current element being iterated over.

Here is the JSFiddle Link for Example # 1.A: http://jsfiddle.net/wcRmd/

 

Example # 1.B

In Example # 1.B, we take advantage of two additional features that the jQuery().each method has to offer. The callback takes two optional arguments: the index of the current element being iterated over, and the element itself. In our example, we add the index of each element to its text, and we do so by referencing ‘element’ instead of ‘this’. Keep in mind that ‘element’ is just what we decided to name that argument variable. We could just have easily named it ‘foo’ or ‘glove’. It doesn’t matter what you name these variables, just as long as you are aware of what they are.

We also used the .hasClass() method to see if each element had the “skip” class. This was just a way to illustrate the fact that while you CAN do things to each element inside of the callback function, you can also choose not to. There are numerous ways that you can organize this kind of logic. Using the ‘skip’ class was merely a ‘quick and dirty’ approach.

Here is the JSFiddle Link for Example # 1.B: http://jsfiddle.net/9C8He/

jQuery.each()

Example # 2.A

In Example # 2A, we pass-in two arguments to the static jQuery.each() method: an array and an anonymous callback function. The array has three elements, and the callback merely outputs the value of each array element to the console. Pretty simple stuff.

Here is the JSFiddle Link for Example # 2.A: http://jsbin.com/epanov/1/edit

 

Example # 2.B

In Example # 2.B, we provide an object as the first argument to the jQuery.each() method. When iterating over an object, the jQuery.each() method will return the property name for ‘index’. This is a brilliant approach, as it provides a very flexible alternative to the native JavaScript “for/in” loop.

Here is the JSFiddle Link for Example # 2.B: http://jsbin.com/examuz/1/edit

 

Example # 2.C

In Example # 2.C, we provide a jQuery DOM collection as the first argument to the jQuery.each() method. Essentially, this is just like using the jQuery().each() method. Inside of the callback function, ‘index’ can be used to get a numerical reference to the current element being iterated over, and ‘value’ will be the element itself. Brilliant.

NOTE: You may wonder why the last two elements have indexes of 0 and 1 respectively. This is because we specified that list items with the ‘weekend’ class should be returned in the collection. So, our jQuery collection object contains only two elements (‘saturday’ and ‘sunday’).

Here is the JSFiddle Link for Example # 2.C: http://jsfiddle.net/XjxvZ/

 

Summary

In this article we learned the difference between the jQuery.each() and jQuery().each() methods. We also discovered that while they do differ, the jQuery.each() is flexible enough to provide the same functionality as jQuery().each() if needed.

Helpful Links for jQuery().each() and jQuery.each()

jQuery().each()

http://api.jquery.com/each/

jQuery.each()

http://api.jquery.com/jQuery.each/

JavaScript Callback Functions – The Absolute Basics

Functions

JavaScript LogoCallbacks are a critical tool for properly handling asynchronous events in JavaScript.

Timing is one of the most difficult techniques to master in JavaScript. At first, many look to the setTimeout() method to address the asynchronous nature of JavaScript. But that is most often not the best approach. The concept of a callback function is one of the things that makes JavaScript such a special language.

In order to understand callbacks, it is important to be aware that functions are first class citizens in JavaScript. This means (among other things) that a function can be passed as a value to another function. The upside to this is the fact that if you call function A, and pass it function B as an argument, then inside of function A, you can execute function B. That’s really what it all boils down to: You call a function, and pass it another function. And inside of the first function, when an event that you need to complete has completed, you then “call back” to the function that was passed in.

While you can pass a named function as an argument, quite often you will see an anonymous function passed. Before we demonstrate a callback function, let’s demonstrate why they are so helpful in JavaScript.

Example # 1

PHP FIle:

Client-side JavaScript:

In Example # 1, we have two chunks of code: A server-side page that sleeps for three seconds, and then returns a JavaScript file. That JavaScript file simply outputs a message to the console.

When the script loads, it outputs a message to the console (message # 1). We want that message to be output before the 2nd message. The problem is that the script loading process is asynchronous; it could take 200ms, it could take five minutes. I’ve forced the PHP page that returns the JavaScript to “sleep” for three seconds, to exaggerate the effect. But the bottom line is: we don’t know how long that script loading process will take, which means that we have to find a way to execute message # 2 only after the script has finished loading.

Here is a JSFiddle link for Example # 1: http://jsfiddle.net/CZeLv/

Example # 2

In Example # 2, we pass an anonymous function to the getScript() method. Inside of getScript(), we take advantage of the fact that any dynamically loaded script element has an “onload” event. We assign that event to the callback that was passed-in. This means that when the script has successfully loaded, we execute the callback. As a result, we have complete control over the timing of events, even though the entire process is asynchronous. What happens is that message # 1 executes first, and then message # 2. This is what we want.

Here is a JSFiddle link for Example # 2: http://jsfiddle.net/dfCM2/

What if the script that we are loading has properties and methods that we need to act upon once the script is available? In Example # 3, we demonstrate how using a callback allows us to call a method that does not exist before the script is loaded, but we are able to control the timing of when it is called, so that it works every time.

Example # 3

PHP File:

Client-side JavaScript:

In Example # 3, after the PHP file “sleeps” for three seconds, it adds a new method to the window object. That method returns a secret word. We need access to that secret word in our page, but we need to make sure that we don’t try to call the method getSecretWord() until it is available. So by passing a callback to the getScript() function, we yield control to getScript() and basically ask it to fire our callback for us. Inside of getScript(), the script’s onload event is assigned to the callback, which means we only attempt to execute getSecretWord() once we know for sure that it exists (because the script’s onload event fired).

So the important thing to keep in mind here is that if the script we are loading takes five minutes to return, or never returns, it does not matter. Our callback will only fire when that script successfully loads. While it is loading, the user still has complete access to the browser. That is really important.

Here is a JSFiddle link for Example # 3: http://jsfiddle.net/fAn4g/

Summary

In this article, we covered the very basics of JavaScript callback functions. We learned that functions are first-class citizens in JavaScript, and can be passed to and from functions. We looked at an example of why callbacks are so critical to the JavaScript language and how they are an excellent tool for working around the asynchronous nature of the language,

Helpful Links for JavaScript Callback Functions

http://recurial.com/programming/understanding-callback-functions-in-javascript/

http://www.impressivewebs.com/callback-functions-javascript/

http://javascript.about.com/od/byexample/a/usingfunctions-callbackfunction-example.htm