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

Retrieving and posting static dropdown data into mysql database in Zend 2

mysql drop-down-menu zend-framework2

I have several fields in my form that i wish to post to the database. All the other fields bar the dropdown field are all working fine

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.