using jquery's deferred with settimeout

I have a module that has an internal loop (using 'settimeout'). I want to fire a callback each time the timer happens. I tried using jQuery's deferred object with no luck.. Something like:

 $(function(){
    var module = new MyModule();
    $.when(module.init()).then("DO Something");
 });

 function MyModule(){

    this.d = $.Deferred();

}

test.prototype.init = function(){
    clearTimeout(this.next);

    var self = this;

    /*  Do Something */

    self.d.resolve();

    this.next = setTimeout(function(){
        self.init(); /* The problem is here - internal call to self */
    }, 4000);
    return self.d.promise();
};

The problem is that the timer calls the method internally, so I will not have a call to ".then(Do Something);" of the main program. I can use the old school function callback (pass a callback function to the module) but I really wanted to try these great feature.

Thanks,

Yaniv

Answers


A deferred really isn't what you're looking for because that's a one time deal - what you likely want is a Callback list.

jQuery provides that as $.Callbacks() which might be what you're looking for.

function MyModule(){

    this._initCallbacks = $.Callbacks();

}

MyModule.prototype.onInit = function( cb ) {
    if ( typeof cb === "function" ) {
        this._initCallbacks.add( cb );
    }
};

MyModule.prototype.init = function(){
    clearTimeout( this.next );

    var self = this;

    this._callbacks.fire();

    this.next = setTimeout(function(){
        self.init();
    }, 4000);

    return this;
};

$(function(){
    var module = new MyModule();

    module.onInit(function() {
        console.log( "Do something" );
    });

    module.init();
});

JSFiddle: http://jsfiddle.net/SUsyj/


Need Your Help

Possibility of getting Path Coverage by jmockit coverage tool with exclusion of desired paths

unit-testing code-coverage jmockit

I was interested to get path coverage for my code after doing unit testing, but it contains lots of if-else conditions which make the actual number of paths like around 67k so is there any possibil...

MS Access - check sub-form before entry for duplicate

ms-access duplicates

I've got a subform (customersAnswersSub) inside of a main form (customersAnswers). Upon someone entering a new customerAnswersSub entry - I wanted it to check for duplicates first.

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.