JavaScript Logo

Sometimes you have multiple JavaScript functions that you need to execute in a specific order, but do not know the details ahead of time

Both jQuery and Dojo offer their own flavor of “Deferred” functionality. This is a pretty deep topic that, while a bit challenging, offers tremendous power with respect to queuing up an invocation of multiple functions in an orderly manner. One concept that plays into this way of thinking is using the JavaScript array object’s shift() method. It easily fires off some functions in order, even when you don’t know ahead of time how many there will be.

Example # 1

var b = function(){ console.log(“this is function: b”) } var c = function(){ console.log(“this is function: c”) } var foo = [a,b,c]; while (foo.length){ foo.shift().call(); }

In example # 1, we define three functions. Then, we build an array with each element being a reference to one of our functions.  Now, using a while loop, we call each function. There is a cool interplay going on here. For the while loop, as long as foo has length (that is as long as the length of foo does not return a “falsy” value, such as zero), the loop will run. Inside the loop, the JavaScript shift() method not only removes the first element from the array, it also returns that element. So, we chain onto that return value, which is the function itself, and use the JavaScript .call() method, to actually invoke the function. With each iteration of the while loop, the array looses an element. It therefore becomes smaller and smaller until finally,  “foo.length” returns zero, which is “falsy,” and the loop no longer runs.

The end result here is that you can have a list of functions that you can execute, one at a time, in a specified order, and each function runs only once.  A much more practical use for this technique is when you are adding methods to the array (i.e. our “queue”), at run time. You don’t know how many you might add, or what they might do, but you know that you can line ’em up, and fire ’em off!

Summary

Because so much of what the Front End Web Developer deals with happens in the life of a page, there are many circumstances in which you are not sure how many of something will come along. But if you are able to get your hands around such dynamic events, you can handle some pretty cools scenarios. Invoking an unknown number of functions at runtime is such a case. This technique provides a fairly simple way to implement this approach.

Helpful links for the JavaScript Array Object’s shift() Method

http://www.w3schools.com/js/js_obj_array.asp

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift

http://www.bennadel.com/blog/1796-Javascript-Array-Methods-Unshift-Shift-Push-And-Pop-.htm

http://freewebdesigntutorials.com/javaScriptTutorials/jsArrayObject/shiftMethod.htm

 

 

One Comment

Comments are closed.