Jonny White
Jonny White

Reputation: 875

Efficient function declaration in JavaScript

I have some javascript code that needs to run every 6 seconds that looks like this:

this.y = function()
{
    //some logic that may or may not call y_a or y_b

    this.y_a = function()
    {
         //some logic
    }
    this.y_b = function()
    {
         //some logic
    }

    var self = this;
    setTimeout(function(){ self.y(); }, 6000);
}

y_a and y_b are not needed outside the scope of y.

As this function is being called every 6 seconds, is it significantly inefficient to keep redeclaring y_a and y_b? Or should I define them once outside the scope of y?

Upvotes: 0

Views: 46

Answers (4)

Pankaj Goyal
Pankaj Goyal

Reputation: 1548

If you want to call that function in an interval of 6 secs, then better to use setInterval(). Because setTimeout is only for one execution after timeout.

Declare your function y_a and y_b outside y if you have a choice and then add this :-

function y_a() {
}
function y_b() {
}
function y() {
    y_a();
    y_b();
    //calling y_a and y_b
} 
window.setInterval(y,6000) // 6 secs = 6000 ms

For Initial call when page gets refreshed, you need to call that function in ready(). Then after every 6 secs that function will be called automatically.

Upvotes: 0

Pablo Lozano
Pablo Lozano

Reputation: 10342

When JS is being executed, the closer the scope is, the fastest the resolution is. Said that, 6 seconds is an eternity in CPU time.

I'd code it as:

function y () {
    function a() {..}
    function b() {..}

    //calling a and b
}
setInterval(y, 6000); // timeout is for one execution, interval for recurrent executions

Upvotes: 1

Pinoniq
Pinoniq

Reputation: 1385

Yes, it is inefficient to keep redeclaring y_a and y_b. As Crowder allready noted however, 6 seconds timeinterval won't really slow down.

That said, I think you are using a wrong pattern. Instead go for something like this:

y = (function()
{
    //we create the functions inside this anonymous scope
    function y_a()
    {
        //do stuff
    }

    function y_b()
    {
        //do stuff
    }

    //we return a function, that in its turn has access to the scope
    //were the above funcs are delared. They are however hidden for the outside
    return function()
    {
        if ( a )
        {
            y_a();
        } else
        {
            y_b();
        }
    }
})();

setTimeout(function(){ y(); }, 6000);

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074188

As this function is being called every 6 seconds, is it significantly inefficient to keep redeclaring y_a and y_b?

Probably not. Six seconds is a very long interval between calls, in computer terms.

Or should I define them once outside the scope of y?

Probably, unless you have a good reason for redefining them each time.

Upvotes: 2

Related Questions