jquery setInterval() 可以控制执行次吗?
$(document).ready(function(){iCount=setInterval("startRequest()",2000);});functionsta...
$(document).ready(function () {
iCount = setInterval("startRequest()",2000);
});
function startRequest() {
$.ajax({
type: "POST",
url: "test",
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function (XMLHttpRequest) {
},
success: function (msg) {
if(msg != ''){
clearInterval(iCount);
$("#data").text('');
$("#data").append(msg);
}
},
});
}
我这样可以按间隔时间去请求数据,当请求到后停止,但我想让它请求到N次后还没请求到时,也能停止,谢谢! 展开
iCount = setInterval("startRequest()",2000);
});
function startRequest() {
$.ajax({
type: "POST",
url: "test",
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function (XMLHttpRequest) {
},
success: function (msg) {
if(msg != ''){
clearInterval(iCount);
$("#data").text('');
$("#data").append(msg);
}
},
});
}
我这样可以按间隔时间去请求数据,当请求到后停止,但我想让它请求到N次后还没请求到时,也能停止,谢谢! 展开
展开全部
$(document).ready(function () {
var i = 9;
iCount = setInterval(function(){
if(!i)clearInterval(iCount);
startRequest();
i--;
},2000);
});
function startRequest() {
$.ajax({
type: "POST",
url: "test",
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function (XMLHttpRequest) {
},
success: function (msg) {
if(msg != ''){
clearInterval(iCount);
$("#data").text('');
$("#data").append(msg);
}
}
});
}
追问
谢谢,您这写法有趣一些,我自己也想了下,这么实现了:
在 startRequest()外面定义i 在函数里每次减一,到0时执行clearInterval(icount).
追答
可以定义在外面,但是这样没有实际意义的变量最好不要定义在最外面,你可以使用封包
(function(){//封包
var iCount,i = 9;
$(document).ready(function () {
iCount = setInterval(startRequest, 2000);
});
function startRequest() {
if(!i--)clearInterval(iCount);
$.ajax({
type: "POST",
url: "test",
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function (XMLHttpRequest) {
},
success: function (msg) {
if(msg != ''){
clearInterval(iCount);
$("#data").text('');
$("#data").append(msg);
}
}
});
}
})();
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询