2017-05-21 1 views
0

내 코드에는 임의의 시간 간격으로 하나씩 실행해야하는 세 개의 간격이 있습니다.Javascript - 올바른 순서로 적은 간격

var times = Math.floor((Math.random() * 3) + 2); 
    var turn = 0; 
    var schemaInterval1 = setInterval(function(){ 
     console.log('first'); 
     turn++; 
     if(turn == times) 
     { 
      times = Math.floor((Math.random() * 3) + 2); 
      turn = 0; 
      clearInterval(schemaInterval1); 
     } 
    },1000); 
    var schemaInterval2 = setInterval(function(){ 
     console.log('second'); 
     turn++; 
     if(turn == times) 
     { 
      times = Math.floor((Math.random() * 3) + 2); 
      turn = 0; 
      clearInterval(schemaInterval2); 
     } 
    },1000); 
     var schemaInterval3 = setInterval(function(){ 
     console.log('third'); 
     turn++; 
     if(turn == times) 
     { 
      times = Math.floor((Math.random() * 3) + 2); 
      turn = 0; 
      clearInterval(schemaInterval3); 
     } 
    },1000);  

간격 내에서 코드를 실행할 때마다 차례 값에 1을 더합니다. turn과 times 값이 같을 때 나는 그것들을 모두 재설정했다. 현재 작업 간격을두고 다른 간격으로 건너 뜁니다. 어떻게 올바른 순서로 그 간격을 넣어 내 코드를 다시 작성할 수 있습니다

first 
second 
third 
first 
second 
first 
(4)second 

먼저 마무리가 될 때까지 다른 작업을 허용하지 않습니다 : 그러나 불행하게도 그들은 내가 그 메시지가 올바른 순서로 내 콘솔에서 작동하지 않습니다 태스크?

+1

한 간격으로 전체 코드를 넣어 : 이 코드는 당신이 찾고있는 무엇을해야합니까? – Siphalor

답변

0

모든 간격을 동시에 시작하십시오. 시리즈로 실행하려면 이전 세트를 지울 때 시작해야합니다.

var times = Math.floor((Math.random() * 3) + 2); 
 
var turn = 0; 
 
var intervalNumber = 1; 
 
var intervalTime = 1000; 
 
var numberOfIntervals = 3; 
 
function instantiateInterval() { 
 
    if (intervalNumber <= numberOfIntervals) { 
 
    console.log('Timer number: ' + intervalNumber); 
 
    var interval = setInterval(function() { 
 
     turn++; 
 
     if(turn === times) { 
 
     times = Math.floor((Math.random() * 3) + 2); 
 
     turn = 0; 
 
     clearInterval(interval); 
 
     instantiateInterval(); 
 
     } 
 
    }, intervalTime); 
 
    intervalNumber++; 
 
    } 
 
} 
 
instantiateInterval();

관련 문제