Mindaugas Jakubauskas
Mindaugas Jakubauskas

Reputation: 439

jquery don't run same function twice on the same time

I've got a code.

setInterval(somefunc, 1000);

function somefunc() {
    curid = $(".chat-message:last").attr("id");
    $.post("http://blah.com/blah.php&last_msg_id=" + curid, function (data) {

        $('.chat-messages').append(data);
    });
}

function saveChat() {
    var texts = $('#chatText').val();

    var request = $.ajax({
        type: "POST",
        url: "http://blah.com/submit.php",
        data: {
            text: texts
        },
        dataType: "html"
    });

    request.done(function (msg) {
        somefunc();
    });
}

The problem is that sometimes saveChat is executed at the same time as interval and the information somefunc appends to .chat-messages duplicates. How could I avoid it? I need a function which allows to execute function somefunc() again only when previous execution of somefunc() is completely finished. Or just not to allow execute function somefunc() twice at the same time.

Upvotes: 0

Views: 677

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191729

Don't use setInterval, but nest setTimeout:

setTimeout(somefunc, 1000);
function somefunc() {
    //snip
    $.post().done(function () { setTimeout(somefunc, 1000); });
}

Upvotes: 5

Related Questions