2016-11-20 5 views
0

아래 코드를 사용하여 스프라이트에 애니메이션을 적용하려하지만 루프의 다음 반복 단계로 이동하기 전에 1 초 정도 기다리는 대신 애니메이션이 스프라이트의 첫 번째 이미지에서 마지막 약 1 초. 아무도 내가 염두에두고있는대로 작동하도록 코드를 변경하는 방법을 말해 줄 수 있습니까? 감사!CSS 스프라이트 애니메이션에 대한 setInterval

preview = setInterval(animation,1000); 
counter = 0; 

function animation() { 
    while (counter < 81){ 
     position = counter * 1.25; 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
     counter ++; 
    } 
}; 

preview; 

답변

1

루프 밖으로의 동안 부분을 가져 가라.

function animation() { 
    if (counter < 81){ 
     position = counter * 1.25; 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
     counter ++; 
    } else { 
     clearInterval(preview); /* this will stop the interval timer, since you won't need it after 80 repetitions. */ 
     preview = null; 
    } 
} 
2

while 루프는 첫 번째 간격 호출에서 모든 일이 발생하도록합니다. 을 제거하고, 당신은 간격에 전적으로 의존 할 수 있습니다 :

preview = setInterval(animation,1000); 
counter = 0; 

function animation() { 
     position = counter * 1.25; 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
     counter ++;   
}; 

preview; 

라이브 예 :

var preview = setInterval(animation,100); 
 
var counter = 0; 
 

 
function animation() { 
 
     position = counter * 1.25; 
 
     $('#ad_1').css({"background-position" : position + "% 0%"}); 
 
     counter ++;   
 
};
div { 
 
    height: 317px; 
 
    width: 50px; 
 
    display: inline-block; 
 
    background: url(https://pbs.twimg.com/profile_images/2186972673/super_mario.jpg); 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="ad_1"></div>