2012-05-05 3 views
6

Momentjs 라이브러리는 매우 멋지지만 몇 가지 간단한 작업을 수행하는 방법에 대한 문서는 매우 명확하지 않습니다. 카운트 다운 타이머를 만들려고하는데 기간 객체를 사용해야한다고 생각합니다. 그러나 어쩌면 어쩌면 영어가 제 첫 번째 언어가 아니기 때문에 어쩌면 이해할 수 없습니다.Momentjs 및 카운트 다운 타이머

var time = 7200; 
var duration = moment.duration('seconds',time); 

setInterval(function(){ 
    //show how many hours, minutes and secods are left 
    $('.countdown').text(duration.format('h:mm:ss')); 
    //this doesn't work because there's no method format for the duration object. 
},1000); 

을 그래서 everysecond가 표시되어야합니다 :

2시 0분 0초

1시 59분 59초

1시 59분 58초

어쨌든이게 내가 원하는 것입니다

01:59:57

...

00:00:00

Momentjs 라이브러리로 어떻게이 결과를 얻을 수 있습니까? 감사합니다.

+0

나는 momentjs 라이브러리를 모른다 , 대신'setInterval'을 원한다고 생각합니다. – pimvdb

+0

Momentjs는 시간과 날짜를 가져 오는 메소드를 제공하지만 아무것도하지 않기 때문에 매초 1 초를 감산하고 setInterval 함수에서 표시하는 자체 스크립트를 만들어야합니다. – Ignas

+0

젠장, 네가 지금 무슨 말하는지 알 겠어. 실수를 수정했습니다. – Ignas

답변

13

duration 객체가 정적의 시간 간격을 나타냅니다, 그리고의 흐름과 함께/감소를 증가시키지 않습니다 시각. 그래서 당신이 그것을 줄이려면, 예를 들어 일초 카운터를 만들거나 매회 duration 개체를 다시 만들어야합니다. 여기에 두 번째 옵션에 대한 코드입니다 :

var time = 7200; 
var duration = moment.duration(time * 1000, 'milliseconds'); 
var interval = 1000; 

setInterval(function(){ 
    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds'); 
    //show how many hours, minutes and seconds are left 
    $('.countdown').text(moment(duration.asMilliseconds()).format('h:mm:ss')); 
}, interval); 
+1

설명과 솔루션을 정확히 +1하고 싶습니다. 감사! – Ignas

2

나는 아주 잘 하나 Momentjs 몰라,하지만 난 당신이 이런 식으로 뭔가를 찾고 생각 :

var time = 7200; 
var duration = moment.duration('seconds',time); 

setInterval(function(){ 
    var countdown = duration.milliseconds(); 
    $('.countdown').text(moment(countdown).format('h:mm:ss')); 
},1000); 
+0

올바른 방향으로 나를 주셔서 감사합니다! – Ignas

1

https://github.com/jsmreese/moment-duration-format 그것 Moment.js 자바 스크립트 날짜 라이브러리에 플러그인이 순간에 포괄적 서식을 추가 할 수는 재생 시간

<script type="application/javascript" src="/js/moment.js"></script> 
<script type="application/javascript" src="/js/moment-duration-format.js"></script> 

<script> 

function startTimer(){ 

var duration = moment.duration({ 
    'hour': 2, 
    'minutes': 0, 
    'seconds': 0 
}); 

var interval = 1; 

var timerID = -1; //hold the id 

var timer = setInterval(function() { 

    if(duration.asSeconds() <= 0){ 
     console.log("STOP!"); 
     console.log(duration.asSeconds()); 
     clearInterval(timerID); 
    } 
    else{ 

    duration = moment.duration(duration.asSeconds() - interval, 'seconds'); 

    $('.countdown').html(duration.format("hh:mm:ss", { trim: false })); 
    } 

}, 1000); 

timerID = timer; 

return timer; 
}; 

//start 
myTimer = startTimer();  

//stop 
//clearInterval(myTimer); 

</script>