Aroniaina Aroniaina - 19 days ago 5
Javascript Question

Javascript stop interval and action after

My proble is about setintervall function. I call a function named

thrice()
when
first()
and
second()
execution is finished. There is no proble with that. The code below :

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();


The output is like this :

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


You see at the end of the output, it's the problem
FUNCTION thrice FINISH
is executed before
FUNCTION thrice RUNNING

Answer

Its because, all the content of function in setInterval is called after 3000 milisec. Its the goal of 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");

If you want fix the order, you have to put console.log("FUNCTION thrice FINISH"); inside the callback function :

var intev = setInterval(function () {
    if (oneFinish && twoFinish) {
        console.log("FUNCTION thrice RUNNING");
        oneFinish = false;
        twoFinish = false;
        clearInterval(intev);
        console.log("FUNCTION thrice FINISH");
    }
}, 3000);
Comments