Reputation: 612
I am making a simple chat, it works in different browsers but setTimeout
keeps firing, and I want it to fire only once as it is pointless to keep firing and I believe also it would cause more stress on the server.
This is the function which is called from somewhere else:
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
setTimeout("chat_load();", 1000);
});
}
I tried something like the following but it just keeps on firing. Also, the function is supposed to fire only when a certain button is clicked, which happens only once every so often.
var c = 0;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
c++;
if (c == 3) {
clearTimeout(t);
}
});
}
Upvotes: 2
Views: 7437
Reputation: 74420
I think you want something like this:
var c = 0, t;
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
clearTimeout(t);
t = setTimeout(chat_load, 1000);
if (++c === 3) {
clearTimeout(t);
c=0;
}
});
}
Upvotes: 2
Reputation: 20189
You can't change variables in a asynchronous function
c++;
wont work
maybe you should do this
function addCount() {
c++;
}
and change c++
to addCount();
so this
var c = 0;
function addCount() {
c++;
}
function chat_load() {
$.post('chat.php', {stage:'load'}, function(data) {
$('#window').html(data);
var t = setTimeout("chat_load();", 1000);
addCount();
if (c == 3) {
clearTimeout(t);
}
});
}
Upvotes: 0