我的问题是关于setintervall函数。当thrice()
和first()
执行完成时,我调用名为second()
的函数。这没有问题。以下代码:
var oneFinish = false;
var twoFinish = false;
function first() {
console.log("FUNCTION first RUNNING");
for (i = 0; i < 5; i++) {
console.log("first " + i);
}
console.log("FUNCTION first FINISH");
oneFinish = true;
}
function second() {
console.log("FUNCTION second RUNNING");
for (i = 0; i < 10; i++) {
console.log("second " + i);
}
console.log("FUNCTION second FINISH");
twoFinish = true;
}
function thrice() {
var intev = setInterval(function () {
if (oneFinish && twoFinish) {
console.log("FUNCTION thrice RUNNING");
oneFinish = false;
twoFinish = false;
clearInterval(intev);
}
}, 3000);
console.log("FUNCTION thrice FINISH");
}
first();
second();
thrice();
输出如下:
FUNCTION first RUNNING
first 0
first 1
first 2
first 3
first 4
FUNCTION first FINISH
FUNCTION second RUNNING
second 0
second 1
second 2
second 3
second 4
second 5
second 6
second 7
second 8
second 9
FUNCTION second FINISH
FUNCTION thrice FINISH
FUNCTION thrice RUNNING
您会看到输出的结束,问题FUNCTION thrice FINISH
在FUNCTION thrice RUNNING
之前执行
答案 0 :(得分:2)
因为,setInterval中函数的所有内容都是在3000 milisec之后调用的。它的目标是setInterval:http://www.w3schools.com/jsref/met_win_setinterval.asp
var intev = setInterval(function () {
if (oneFinish && twoFinish) {
console.log("FUNCTION thrice RUNNING");
oneFinish = false;
twoFinish = false;
clearInterval(intev);
}
}, 3000);
console.log("FUNCTION thrice FINISH");
如果要修复订单,则必须将console.log("FUNCTION thrice FINISH");
放入回调函数中:
var intev = setInterval(function () {
if (oneFinish && twoFinish) {
console.log("FUNCTION thrice RUNNING");
oneFinish = false;
twoFinish = false;
clearInterval(intev);
console.log("FUNCTION thrice FINISH");
}
}, 3000);
答案 1 :(得分:0)
那是因为您在3秒后开始登录,但是您立即记录结束。试试这个:
function thrice() {
var intev = setInterval(function () {
if (oneFinish && twoFinish) {
console.log("FUNCTION thrice RUNNING");
oneFinish = false;
twoFinish = false;
clearInterval(intev);
console.log("FUNCTION thrice FINISH");
}
}, 3000);
}