2011-03-20 6 views
1
(function() { 
    var count = { 
     digit: 0, 
     increment: function() { 
      var interval = setInterval(function() { 
       if (++count.digit == 10) { 
        clearInterval(interval); 
        count.decrement(); 
       } 
       var update = document.getElementById("liveUpdate"); 
       update.innerHTML = count.digit; 
      }, 500); 
     }, 
     decrement: function() { 
      var interval = setInterval(function() { 
       if (--count.digit == -1) { 
        clearInterval(interval); 
       } 
      }, 500); 
     } 
    }; 
    count.increment(); 
})(); 

멈추지 만 내려 가지 않습니까? 무엇이 문제 일 수 있습니까?왜 간단한 자바 스크립트 증가 및 감소 방법이 작동하지 않습니까?

+1

귀하의 코드가 정확한지,하지만 당신은'update' 요소에'digit'를 표시하는 것을 잊지 :

시도 (또는 해당 JSFiddle 확인). – jerone

답변

4

decrement 함수는 아무데도 출력을 업데이트하지 않습니다. 변수 이지만 화면에 표시되지 않습니다.

(function() { 
    var update = document.getElementById("liveUpdate"); 
    var count = { 
     digit: 0, 
     increment: function() { 
      var interval = setInterval(function() { 
       if (++count.digit == 10) { 
        clearInterval(interval); 
        count.decrement(); 
       } 
       update.innerHTML = count.digit; 
      }, 500); 
     }, 
     decrement: function() { 
      var interval = setInterval(function() { 
       if (--count.digit == -1) { 
        clearInterval(interval); 
       } 
       update.innerHTML = count.digit; 
      }, 500); 
     } 
    }; 
    count.increment(); 
})(); 
2

버그가 아니며, 기능입니다 ;-). setInterval()은 지정된 간격 (500ms)으로 루프에서 주어진 함수를 실행합니다. 자세한 내용은 article을 참조하십시오.

관련 문제