Javascript Self-executing Functions

Sat, Dec 18, 2010, by Sarfraz Ahmed

Audio

In this article, I will discuss self-executing functions of javascript and their hidden power with real-world example. We will also see why using setInterval is bad in some situations.

Let’s explore little knows or little used but extremely powerful self-executing functions of javascript.

What is Self-Executing Anonymous Function?

A self-executing anonymous also knows as self-invoking anonymous function runs automatically/immediately when you create it and has no name. Here is the format of typical self-executing anonymous function:

    (function(){
      // some code…
    })()

You must be aware of the fact that javascript functions run immediately when you put () after their names eg:

    doStuff(); // this will run immediately

And:

    doStuff;  // this will not run immediately and can be used as callback

Now because () exist at the end of self-executing anonymous function above, it will run immediately.

Note that you can also write self-executing anonymous function like this:

    function(){
      // some code…
    }()

Using extra braces like before function keyword is simply coding convention and is used even by famous javascript libraries such as jQuery.

Interestingly, if you look at the source code of jQuery, you will see that everything is wrapped in between:

    (function( window, undefined ) {
      // jQuery code
    })(window);

That is as can be seen also a self-executing anonymous function with arguments. A window (and undefined) argument is created and is mapped with global window object at the bottom (window).

What is Self-Executing Function?

Self-Executing function is a named function that runs immediately. Example:

    function foo(){
      // some code…
    }()

Note that now that we have named our function foo, it is not an anonymous function though it still is self-executing function because of () at the end.

How do they run automatically?

This can be best explained through an example. Let’s say in your webpage you have this javascript code:

    function showUp(){
      alert(’Hello There’);
    }

When you visit the page, the showUp function will not get triggered unless you do so by calling the function:

    function showUp(){
      alert(’Hello There’);
    }

    // run the function

    showUp();

However, you can make the function auto-run by making it self-executing function like this:

    (function showUp(){
      alert(’Hello There’);
    })()

Where to use self-executing functions?

One obvious situation is when you want to auto-run a function like I showed in above example but that is trivial. If you are in a situation where you want to run a piece of code repeatedly like updating something in the database based on user interaction or fetching records from database every 10 seconds or you want to load new stories via ajax similar to how facebook does on its homepage or some other similar situation, one would normally go for setInterval function something like this:

    setInterval(doStuff, 10000);

Above, doStuff function will get called every 10 seconds. That is the normal approach most developers seem to go with. However, there is a huge problem with that. The setInterval will call doStuff function exactly at specified time of 10 seconds again and again irrespective of whether doStuff function actually finished doing what it is supposed to do. That is bad and will certainly get you into unexpected results.

That is one example of where setInterval is ^bad^ and should be avoided.

This is exactly where self-executing functions come in handy. We can do the same task with the help of self-executing function along with setTimeout like this:

    (function foo(){
       doStuff;
   
       setTimeout(foo, 10000);
   
    })()

This code will also repeat itself again and again with one difference. setTimeout will never get triggered unless doStuff is finished. A much better approach than using bad setInterval.

You can see the example in action here.

2
Liked it
1 Comments For This Post
  1. Zain Reza Says:

    Awsum articles… Thanks for sharing this .

Leave a Reply
comments powered by Disqus