0

I have assigned 5000 ms to Settimeout but it is executing before assigned time interval.Can any body explain why it is happening.

<script type="text/javascript">
        var getcallback = {
            closure: function (callback, functionparam) {
                return callback.call(functionparam);
            }
        }
        var cleartimeout;
        var startSlideShow =  {
            timerid: 5000,
            startAnimation: function () {
                cleartimeout = setTimeout(getcallback.closure(function () {
                    alert("this is a basic example of chaining methods");
                    this.startAnimation();
                },this), this.timerid);
            },
            stopAnimation:function(){
            }
        }
        startSlideShow.startAnimation();

    </script>
Ajay Beniwal
  • 18,857
  • 9
  • 81
  • 99

2 Answers2

1

Because getcallback.closure() is executing the function right away, you are not storing a reference to a function to call at a later time.

epascarello
  • 204,599
  • 20
  • 195
  • 236
  • i have curiosity about set timeout interval .If function is getting called immediately why the next function is getting called immediately why the interval is not maintained .I just want to know how does it actually work – Ajay Beniwal Jun 27 '12 at 15:57
1

As soon as you call startAnimation, you're calling getcallback.closure, which immediately calls the callback function. To use setTimeout correctly, you need to either have closure return a function, or not use such a strange thing, and instead just use an anonymous function.

Something along the lines of:

var getcallback = {
    closure: function (callback, functionparam) {
        return function() {
            callback.call(functionparam);
        };
    }
}

...

Or, to be cleaner, just:

var cleartimeout;
var startSlideShow =  {
    timerid: 5000,
    startAnimation: function () {
        cleartimeout = setTimeout(function () {
            alert("this is a basic example of chaining methods");
            this.startAnimation();
        }, this.timerid);
    },
    stopAnimation:function(){
    }
}
startSlideShow.startAnimation();
voithos
  • 68,482
  • 12
  • 101
  • 116