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.

2
  • 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, 2013 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. May 31, 2013 at 19:22

1 Answer 1

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);
});
2
  • 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! May 31, 2013 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. May 31, 2013 at 19:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.