Sunday, May 1, 2016

JavaScript references with setTimeout() and setInterval()

In this post contains some tips on using the setTimeout() and setInterval() functions in nested manner and using JavaScript reference in those.

  • setTimeout() is used to call function after period of time.
  • setInterval() is used to call function in a loop of time.

There is function x(){} which need to called after 30 seconds.
setTimeout(x(), 30000);

Now I need to call this function x() in 10 seconds loop of time and first call must to be call after 30 seconds.

setTimeout(
    setInterval(x(), 10000);
}, 30000);

setInterval is executed in a global context, If function x() is declared inside another context with setInterval(). This will call function x() only for one time. it will not loop

setTimeout(
    setInterval(x(), 10000);
}, 30000);

 

JavaScript reference to function with parameters

Better way is calling with reference in such context.

setTimeout(
    setInterval(x, 10000);
}, 30000);

Function x(){} upgraded with function parameter such as function x (a){}.

setTimeout(function() {
    console.log("Starting functions");
    x = x('foo');
    setInterval(x, 10000);
}, 30000);

 

Context change will avoid the looping x function. Here is the best way to achieve this.

setTimeout(function() {
    refx = testme('foo');
}, 5000);

function testme(a) {
    setInterval( function (){x(a);}, 10000);
}

No comments:

Post a Comment