0

I have a piece of javascript code:

var intervalId;
intervalId = setInterval(fetchData, 2000);

$('.campaign-select li').on("click", "a", function(event)
{
    window.clearInterval(intervalId);
    intervalId = setInterval(fetchData_id($(this).data('campaign-id')), 2000);
});

The first setInterval was correct, the function fetchData is correctly loaded each 2 seconds.

But when I click the .campaign-select li a element, the fetchData_id is executed but only once, not repeated as expected with setInterval.

Any help?

Thanks.

mokalovesoulmate
  • 271
  • 2
  • 6
  • 18
  • 1
    Inside the handler, you aren't passing a function to `setInterval` - you're passing: `fetchData_id($(this).data('campaign-id'))` - I don't think `setInterval` will know how to execute that returned value every 2 seconds...You're probably looking for `var that = this; setInterval(function () { fetchData_id($(that).data('campaign-id')) }, 2000);` – Ian May 31 '13 at 19:09
  • Hi Ian, the solution from Karl below is worked, and thank you for notifying that this question is possible duplicate, will do better search on stackoverflow. Thanks. – mokalovesoulmate May 31 '13 at 19:22

1 Answers1

3

You can't pass parameter in the setInterval function.

That being said, you should try this :

$('.campaign-select li').on("click", "a", function(event){
    window.clearInterval(intervalId);
    var $this = $(this)
    intervalId = setInterval(function(){
        fetchData_id($this.data('campaign-id'))
    }), 2000);
});
Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75
  • This one is worked! I never know that `$this.data('campaign-id')` is the solution, because I was trying to set `id = $(this).data('campaign-id')` and assign to `setInterval(fetchData_id(id))` but not working. Thanks again! – mokalovesoulmate May 31 '13 at 19:18
  • 1
    Actually, $this is the var setted before the `setInterval`. It could have been `var joey = $(this)` and still work. $this is not a jQuery thing. – Karl-André Gagnon May 31 '13 at 19:23