2013-10-09 7 views
0

제한 시간이있는 텍스트의 색을 변경하려고합니다. 매 5 초마다 색상이 변경되어야합니다. 방금 ​​작동하지 않습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까?지연 텍스트 색 전환

var rainBowColors = new Array(); 
rainBowColors.push("#FF0000"); //Red: #FF0000 
rainBowColors.push("#FF7F00"); //Orange: #FF7F00 
rainBowColors.push("#FFFF00"); //Yellow: #FFFF00 
rainBowColors.push("#00FF00"); //Green: #00FF00 
rainBowColors.push("#0000FF"); //Blue: #0000FF 
rainBowColors.push("#4B0082"); //Indigo: #4B0082 
rainBowColors.push("#8F00FF"); //Violet: #8F00FF 
var rainbowCounter = 0; 

for (var counter = 0; counter < 1000; counter++) 
{ 
    //Easter :) 
    //var timeOut = setTimeOut(function(){ 
    jQuery(".text").css("color", rainBowColors[rainbowCounter]); 
    //}, 500); 

    //clearTimeOut(timeOut); 

    //Higher Counter 
    rainbowCounter++; 

    //Reset counter 
    if (rainbowCounter == rainBowColors.length) 
    { 
     rainbowCounter = 0; 
    } 
} 

전체 예 : http://jsfiddle.net/xLS25/

답변

1

가 귀하의 질문에 대답하려면 : 코드의 색상 변화를 수행 다만 방법에 대한 빠른 눈이 볼 수 있도록. 루프는 모든 반복 (매우 빠름)에서 시간 초과가 실행되는 1000 번의 모든 반복을 통해 실행되며, 동시에 모든 것이 동시에 겉보기에는 해결할 수 있습니다 (너무 빨리 볼 수는 없습니다). 가장 중요한 점은, 타이머가 두 번째로 트리거되면 타이머가 비 순차적이기 때문에이 병렬로 에 똑딱 거리고 있다는 것입니다. 여기서 찾고자하는 것은 타이머가 순차적으로 시작하는 것입니다. 희망이 의미

대신 시간 제한

var rainBowColors = new Array(); 
rainBowColors.push("#FF0000"); //Red: #FF0000 
rainBowColors.push("#FF7F00"); //Orange: #FF7F00 
rainBowColors.push("#FFFF00"); //Yellow: #FFFF00 
rainBowColors.push("#00FF00"); //Green: #00FF00 
rainBowColors.push("#0000FF"); //Blue: #0000FF 
rainBowColors.push("#4B0082"); //Indigo: #4B0082 
rainBowColors.push("#8F00FF"); //Violet: #8F00FF 
var rainbowCounter = 0; 

var interval = setInterval(function(){ 
    jQuery(".text").css("color", rainBowColors[rainbowCounter]); 

    rainbowCounter++; 

    //Reset counter 
    if (rainbowCounter == rainBowColors.length) 
    { 
     rainbowCounter = 0; 
    } 
},100); 

http://jsfiddle.net/xLS25/2/

P.S.의 setInterval을 사용해보십시오합니다 이 배열 선언은 귀하의 것과 동일하지만 조금 더 간결합니다. 당신은 싶어 대신 사용할 수 있습니다 :

var rainBowColors = [ 
    "#FF0000", //Red 
    "#FF7F00", //Orange 
    "#FFFF00" //Yellow 
    // ... add other colors 
]; 
+0

감사를 시도하고 :) – VRC

+0

아무 문제입니다. 그건 그렇고, 배열을 리터럴로 선언하고 싶지 않은 이유가 있습니까? (내 대답은 P.S.를 참조하십시오) –

1

또한 explaination를 솔루션이

setInterval(function(){ 
    jQuery(".text").css("color", rainBowColors[rainbowCounter]); 
    rainbowCounter++; 
    //Reset counter 
    if (rainbowCounter == rainBowColors.length) 
    { 
     rainbowCounter = 0; 
    } 
},500); 
0
var rainBowColors = new Array(); 
rainBowColors =["#FF0000","#FF7F00","#FFFF00","#00FF00","#0000FF","#4B0082","#8F00FF"]; 

var rainbowCounter = 0; 

function changeColor(){ 

    $(".text").css("color", rainBowColors[rainbowCounter]); 


} 
setInterval(function(){ 

     if (rainbowCounter != rainBowColors.length) 
     { 
      rainbowCounter++; 
      changeColor(); 
     } 
     else{ 
      rainbowCounter = 0; 
      changeColor(); 
     } 
    }, 500);