Search code examples
ajaxauto-update

Auto-repeating AJAX function doesn't work


I'm looking to repeat this function every five seconds:

  function check_votes(id) {  
        $.ajax({
            type: 'POST',
            url: 'check_votes.php',
            data: 'checkvotes='+id,
            timeout: 0,
          success: function(data) {
          window.setTimeout(check_votes(id), 5000);
            $('.vote_count_'+id).show();
            $('.vote_count_'+id).html("("+data+" votes so far)");
          }
        });
        return false;
  };

Why doesn't this line do the trick:

 window.setTimeout(check_votes(id), 5000);

In fact, it breaks it, so I need to use the following line:

 window.setTimeout(check_votes, 5000);

But that allows for the script to run initially, but I get no auto-repeating.


Solution

  • window.setTimeout(check_votes(id), 5000);
    

    is wrong because check_votes(id) immediately invokes the function, whereas the setTimeout method expects you to pass it a function pointer as first argument.

    window.setTimeout(check_votes, 5000);
    

    is wrong because you are not passing the check_votes function the id parameter and I guess your AJAX call crashes as it's missing it.

    So try the following:

    window.setTimeout(check_votes, 5000, id);
    

    Notice how we are passing the id parameter to the check_votes callback.

    You can pass an arbitrary number of arguments using this overload:

    var timeoutID = window.setTimeout(func, delay, [param1, param2, ...]);