最近我正在开发一个使用SetInterval和SetTimeout
的项目这是简单的代码: (注意:functionB,functionC与jquery ajax请求有关)
function functionB() {
jQuery.ajax({
type: 'POST',
url: 'https://MYHOSTNAME',
headers: {
'Content-Type': 'XXX',
'Accept': 'XXX'
},
data: MYDATA,
dataType: 'html',
success: function (data, status, xhr) {
var RESPONSEDATA = data;
//true if match my special string
var Compare = RESPONSEDATA.indexOf(MYSTRING) > -1;
if (Compare === true){
//stop the loop
clearInterval(loop1);
}
}
});
}
function Main(){
functionA();//can be anything
var loop1 = setInterval(function () {
setTimeout(functionB, 1000);
setTimeout(functionC, 1000);
}, 3000);
functionD();//can be anything
setTimeout(Main, 16000);
}
main();
我正在尝试确保一旦loop1用clearInterval结束就会执行functionD,当functionB和functionC仍处于循环状态时它不能被执行,并且只有当执行functionD时,函数Main才会等待16000ms然后重新开始。
我尝试了很多方法使用setInterval和setTimeout但没有运气。 任何javascript专家都知道如何做到这一点?
答案 0 :(得分:1)
如果你想要这个:
为循环添加一个活动检查
var loop1;
function functionB() {
jQuery.ajax({
type: 'POST',
url: 'https://MYHOSTNAME',
headers: {
'Content-Type': 'XXX',
'Accept': 'XXX'
},
data: MYDATA,
dataType: 'html',
success: function (data, status, xhr) {
var RESPONSEDATA = data;
//true if match my special string
var Compare = RESPONSEDATA.indexOf(MYSTRING) > -1;
if (Compare === true){
//stop the loop
clearInterval(loop1);
loop1 = false;
}
}
});
}
function aliveCheckOfLoop(){
if(loop1){
addTimeout(aliveCheckOfLoop, 500);
}else{
functionD();//can be anything
setTimeout(Main, 16000);
}
}
function Main(){
functionA();//can be anything
loop1 = setInterval(function () {
setTimeout(functionB, 1000);
setTimeout(functionC, 1000);
}, 3000);
aliveCheckOfLoop();
}
main();
答案 1 :(得分:0)
另一种方法是将主函数拆分为零件,并在清除循环后调用第二部分。
var loop1;
function functionB() {
jQuery.ajax({
type: 'POST',
url: 'https://MYHOSTNAME',
headers: {
'Content-Type': 'XXX',
'Accept': 'XXX'
},
data: MYDATA,
dataType: 'html',
success: function (data, status, xhr) {
var RESPONSEDATA = data;
//true if match my special string
var Compare = RESPONSEDATA.indexOf(MYSTRING) > -1;
if (Compare === true){
//stop the loop
clearInterval(loop1);
goOn();
}
}
});
}
function goOn(){
functionD();//can be anything
setTimeout(Main, 16000);
}
function Main(){
functionA();//can be anything
loop1 = setInterval(function () {
setTimeout(functionB, 1000);
setTimeout(functionC, 1000);
}, 3000);
}
main();