Lunar
Lunar

Reputation: 4711

Callbacks for the same function

I want to call a function a number of times providing it with different input on each occasion, however i am trying to ensure the next function call is triggered after the previous one has finished.

for example:

func(1,2);
func(9,3);
func(6,4);
func(5,6);

I have seen callback be coded like;

function1(someVariable, function() {
          function2(someOtherVariable);
        });

But this only works when calling a second function, i tried chaining the functions but this only allows me to run a set number of functions.

Is there a way i can apply some kind of call back to the same function?

note:: the function just adds a class.

func(x, y){
   $("#block").addClass("class");
    setTimeout(function(){ 
         $("#block").removeClass("class");
     },1000);
};

Upvotes: 5

Views: 1218

Answers (3)

Ajay Singh Beniwal
Ajay Singh Beniwal

Reputation: 19037

I think we should solve this problem using promise pattern available in jquery which allow chaining of callbacks without complex syntax pls see the below pseudo code for reference

function func(value1, value2) {
            var deffered = jQuery.Deferred();
            alert(value1);
            deffered.resolve();
            return deffered;
        }

jQuery.when(func(1, 2)).then(func(2, 3)).then(func(3,4));

Upvotes: 0

Esailija
Esailija

Reputation: 140210

function func(x,y,callback) {
    console.log(x,y);
   $("#block").addClass("class");
    setTimeout(function(){ 
         $("#block").removeClass("class");
         callback();
     },1000);
};

var params = [
    [1,2],
    [9,3],
    [6,4],
    [5,6]
], i = 0;

function fn() {
    if( params[i] ) {
        func( params[i][0], params[i++][1], fn );
    }
}

fn();

Will go as long as there are params left.

Fiddle : http://jsfiddle.net/sabithpocker/dQX6s/

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You could modify the func function with an additional parameter which will represent a callback executed when the function succeeds:

func(x, y, finished) {
    $("#block").addClass("class");
    window.setTimeout(function() {
        $("#block").removeClass("class");
        finished();
    }, 1000);
};

and then chain the calls:

func(1, 2, function() {
    func(9, 3, function() {
        func(6, 4, function() {
            func(5, 6, function() {
                alert('all done');
            });
        });
    });
});

Upvotes: 2

Related Questions