Stopping a Javascript setInterval that is delayed by a setTimeout

I'm having issue with this jsfiddle snippet:

http://jsfiddle.net/y45jN/7/

var mainFunction = function() {
    this.text;
    this.repeater;
}

var repeatEvery = function(func, interval) {

    var now = new Date();
    var delay = interval - now % interval;

    function start() {
        var intervalID = setInterval(func, interval);
        func(intervalID);
    }

    setTimeout(start, delay);

};

mainFunction.prototype.start = function(printText) {
    this.text = printText;
    var self = this;

    var func = function(intervalID) {
        if(intervalID){
            this.repeater = intervalID;
        }
        document.getElementById('test').innerHTML += this.text + '<br/>';
    };  

    repeatEvery(_.bind(func, this),1000);
}

mainFunction.prototype.stop = function() {
    clearInterval(this.repeater);
}

var test = new mainFunction();
test.start('hello');

setTimeout(test.stop,10000);

My goal is to call the stop function and stop the Interval that has been set by the start function.

Answers


You need to do

setTimeout(function(){ test.stop()}, 10000)

or

setTimeout(test.stop.bind(test), 10000); //Bind method is not available in IE8 though

instead of

 setTimeout(test.stop, 10000);

The reason for this is that Javascript loses track of the "this" when you pass a callback to a function.


Need Your Help

Arduino returning more responses than queries have been sent

bash serial-port arduino stty

I have a problem when using Arduino to post data to Pachube. The Arduino is configured to return JSON data for the temperature when you send a 't' and return JSON data for the light level when you ...

Robot Framework - performing multiple keywords after running keyword if

selenium-webdriver robotframework

I am trying to execute multiple keywords if a condition evaluates as true.