【问题标题】:jquery don't run same function twice on the same timejquery不要在同一时间两次运行相同的功能
【发布时间】:2013-02-08 16:45:04
【问题描述】:

我有一个代码。

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();
    });
}

问题是有时 saveChat 与 interval 同时执行,并且 somefunc 附加到 .chat-messages 的信息重复。我怎么能避免呢?我需要一个函数,它只允许在之前的 somefunc() 执行完全完成时再次执行函数 somefunc() 。或者只是不允许同时执行函数 somefunc() 两次。

【问题讨论】:

  • 我认为重新考虑你的概念会更好。
  • 在javascript中,什么都不会同时发生,它是单线程的。
  • 但是 jquery 的速度不够快,无法在 somefunc 再次启动之前追加数据..

标签: jquery ajax


【解决方案1】:

不要使用setInterval,而是嵌套setTimeout

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多