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.
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.is wrong because you are not passing the
check_votesfunction the id parameter and I guess your AJAX call crashes as it’s missing it.So try the following:
Notice how we are passing the
idparameter to thecheck_votescallback.You can pass an arbitrary number of arguments using this overload: