jquery don';t在同一时间运行同一函数两次
我有密码jquery don';t在同一时间运行同一函数两次,jquery,ajax,Jquery,Ajax,我有密码 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
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消息重复。我怎样才能避免呢?我需要一个函数,该函数只允许在上一次执行somefunc()完全完成时再次执行函数somefunc()。或者不允许同时执行函数somefunc()两次。不要使用
setInterval
,而是使用nestsetTimeout
:
setTimeout(somefunc, 1000);
function somefunc() {
//snip
$.post().done(function () { setTimeout(somefunc, 1000); });
}
不要使用
setInterval
,而是使用nestsetTimeout
:
setTimeout(somefunc, 1000);
function somefunc() {
//snip
$.post().done(function () { setTimeout(somefunc, 1000); });
}
我认为最好重新考虑一下你的概念。在javascript中,没有什么事情是同时发生的,它是单线程的。但是jquery不够快,无法在somefunc再次启动之前追加数据。我认为最好重新考虑一下你的概念。在javascript中,没有什么事情是同时发生的,它是单线程的。但是jquery速度不够快,无法在再次启动somefunc之前追加数据。。