wowzuzz
wowzuzz

Reputation: 1388

Having function as argument in setInterval

I'm simply trying to pass a function to a setInterval function. Doesn't seem to be working with my code. Right now the code below works at first, but how would I pass my function parameters when calling the setInterval function?

//Works here

ajaxUpdateOne(function(countOne,countTwo) {
    var itemCount = countOne;
    var totalCount = countTwo;
    console.log(itemCount);
    console.log(totalCount);
});

//Does not work here.

var myVar = ajaxUpdateOne(function(countOne,countTwo) {
    var itemCount = countOne;
    var totalCount = countTwo;
    console.log(itemCount);
    console.log(totalCount);
});

setInterval(myVar,8000);

Upvotes: 1

Views: 76

Answers (2)

Alex Pakka
Alex Pakka

Reputation: 9706

While the code you posted is partial, and it is not clear what ajaxUpdateOne() does, I am assuming it calls $.ajax() and updates the page based on the response results. However, to be able to pass parameters into the function called later in setInterval(), following construct can be used:

var deferredUpdate = function(countOne, countTwo) {
  return function() { ajaxUpdateOne(countOne, countTwo); }
}


setInterval(deferredUpdate(42,3), 8000);
setInterval(deferredUpdate(1,2), 2000);

The trick here is that your deferredUpdate() returns a function itself, not a value. However the parameters for this resulting function are bound in the particular closure. This is one of the basic techniques in functional programming.

Upvotes: 2

Satpal
Satpal

Reputation: 133403

Currently you are calling ajaxUpdateOne() with anonymous function as an argument. myVar is not a function.

Change Your code as

var myVar = function () {
    ajaxUpdateOne(function (countOne, countTwo) {
        var itemCount = countOne;
        var totalCount = countTwo;
        console.log(itemCount);
        console.log(totalCount);
    });
}
setInterval(myVar, 8000);

Upvotes: 3

Related Questions