dzumla011
dzumla011

Reputation: 612

setTimeout keeps firing, how to make it fire only once?

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

Answers (2)

A. Wolff
A. Wolff

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

iConnor
iConnor

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

Related Questions