2016-11-14 8 views
-3

私のprobleはsetintervall機能についてです。 first()second()実行が終了したら、thrice()という関数を呼び出します。それには賛成できません。以下のコード:JavaScriptの停止間隔とアクション後

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

あなたが非同期について聞いたことがありますか? –

+0

はい、聞いたことがあります。なぜdownvote?もっと説明したいですか?あるいは、質問を嫌うのはなぜですか? – Aroniaina

答えて

2

これは、setIntervalの関数のすべての内容が3000ミリ秒後に呼び出されるためです。 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

問題を修正せず、説明しただけです。 – Feathercrown

+0

答えをありがとう、それは私を邪魔する解決策ではありません!しかし説明。 – Aroniaina

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); 
} 
+0

ありがとう、私はあなたが私に説明を与えることを知っているが、私は利他のために2つの答えを受け入れることができません私は@ali_o_kanを選択 – Aroniaina

+0

それは彼が今よりも完全です。 – Feathercrown

関連する問題