Javascript停止间隔和之后的操作
我的问题是关于setintervall函数。当Javascript停止间隔和之后的操作,javascript,setinterval,Javascript,Setinterval,我的问题是关于setintervall函数。当first()和second()执行完成时,我调用名为trice()的函数。这没有问题。代码如下: var oneFinish = false; var twoFinish = false; function first() { console.log("FUNCTION first RUNNING"); for (i = 0; i < 5; i++) { console.log("first " + i);
first()
和second()
执行完成时,我调用名为trice()
的函数。这没有问题。代码如下:
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();
您可以在输出的末尾看到,问题在于
函数三次完成
在函数三次运行之前执行
这是因为您在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);
}
这是因为,setInterval中函数的所有内容都是在3000毫秒后调用的。这是setInterval的目标: 如果你想修改顺序,你必须把
console.log(“函数三次完成”)代码>在回调函数中:
var intev = setInterval(function () {
if (oneFinish && twoFinish) {
console.log("FUNCTION thrice RUNNING");
oneFinish = false;
twoFinish = false;
clearInterval(intev);
console.log("FUNCTION thrice FINISH");
}
}, 3000);
你听说过异步吗?是的,我听说过。为什么要投否决票?需要更多的解释吗?或者只是不喜欢这个问题或者为什么?你没有解决问题,只是解释了它。谢谢你的回答,这不是困扰我的解决方案!但是解释。谢谢你,我知道你给了我解释,但我不能接受2个答案,因为利他主义,我选择了@ali_o__kant这很好,现在他的比我的更完整。
var intev = setInterval(function () {
if (oneFinish && twoFinish) {
console.log("FUNCTION thrice RUNNING");
oneFinish = false;
twoFinish = false;
clearInterval(intev);
}
}, 3000);
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);