Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jquery done on "non-ajax" function

Can I use jquery done() on "non-ajax" functions. I get the error Uncaught TypeError: Cannot call method 'done' of undefined when I try to do something like this.

function countThreeSeconds() {
    var counter = 0,
    timer = setInterval(function () {

        if (counter == 3) {
            console.log("All done. That was three seconds.");
            window.clearInterval(timer);

        } else {
          console.log("Not there yet. Counter at: " + counter);
        }
        counter++;
    }, 1000);

}

(function(){
  var timer = countThreeSeconds().done(function(){
     alert("done");
  });

}());

Thanks

JSBIN

like image 807
1252748 Avatar asked Apr 18 '13 21:04

1252748


1 Answers

Make the non-ajax function return a promise object.

function countThreeSeconds() {
    var counter = 0,
    deferred = $.Deferred(),
    timer = setInterval(function () {

        if (counter == 3) {
            console.log("All done. That was three seconds.");
            window.clearInterval(timer);
            deferred.resolve();

        } else {              
            console.log("Not there yet. Counter at: " + counter);
            deferred.notify(counter);
        }
        counter++;
    }, 1000);
    return deferred.promise();

}

(function(){
  var timer = countThreeSeconds().done(function(){
     alert("done");
  }).progress(function(i){
     console.log("in progress...",i);
  });

}());
like image 148
Kevin B Avatar answered Oct 27 '22 04:10

Kevin B