2012-09-19 3 views
7

단추를 클릭 할 때마다 00:00:00 형식으로 타이머를 시작하는이 함수가 있습니다. 하지만 기능을 재개하고 일시 중지하는 방법을 모르겠습니다. 도움이 될 수 있다고 생각되는 일부 발췌 문장을 발견했지만 그 작업을 할 수 없었습니다. 나는 js에서 객체를 사용하는 것에 익숙하지 않다.타이머를 일시 중지했다가 다시 시작하려면 어떻게합니까?

function clock() { 
    var pauseObj = new Object(); 

    var totalSeconds = 0; 
    var delay = setInterval(setTime, 1000); 

    function setTime() { 
    var ctr; 
    $(".icon-play").each(function() { 
     if ($(this).parent().hasClass('hide')) ctr = ($(this).attr('id')).split('_'); 
    }); 

    ++totalSeconds; 
    $("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds/3600))); 
    $("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds/60) % 60))); 
    $("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds % 60))); 
    } 
} 

패드() 단지 선도 추가합니다 제로

답변

18

클럭 개체를 만드는 것이 더 좋을 것이라고 생각합니다. 코드를 참조하십시오 (: http://jsfiddle.net/f9X6J/ 데모 참조)

var Clock = { 
    totalSeconds: 0, 

    start: function() { 
    var self = this; 

    this.interval = setInterval(function() { 
     self.totalSeconds += 1; 

     $("#hour").text(Math.floor(self.totalSeconds/3600)); 
     $("#min").text(Math.floor(self.totalSeconds/60 % 60)); 
     $("#sec").text(parseInt(self.totalSeconds % 60)); 
    }, 1000); 
    }, 

    pause: function() { 
    clearInterval(this.interval); 
    delete this.interval; 
    }, 

    resume: function() { 
    if (!this.interval) this.start(); 
    } 
}; 

Clock.start(); 

$('#pauseButton').click(function() { Clock.pause(); }); 
$('#resumeButton').click(function() { Clock.resume(); }); 
+0

@Speransky 감사합니다. 이 방법을 사용하면 버튼을 클릭하여 일시 중지하거나 다시 시작할 수 있습니까? – esandrkwn

+1

다시 한번 감사드립니다. 나는 이것을 위해 일하고있다. – esandrkwn

+0

나는 자기의 사용법을 이해할 수 없다 ... diff 장소에서 이것은 다른 의미를 가지고있다 ... 나는 조금 혼란 스럽다. 설명해 주시겠습니까?이 http://jsfiddle.net에 대한 다른 접근법을 가지고 있습니다./wMJuQ/ –

0

사용 window.clearIntervalsetInterval()를 사용하여 설정 한 반복 작업을 취소 할 수 있습니다.

clearInterval(delay); 
+0

가 어떻게 setTime (부터 다시 시작 것) 기능 시계 내부에()? – HeatfanJohn

+0

@HeatfanJohn '일시 중지'의 의미에 따라 다르지만, 디스플레이를 일시 중지하고 타이머를 계속 실행하려면 'clearInterval'을 사용하지 말고 html 콘텐츠 표시를 새로 고침하면됩니다. – xdazz

1

totalSeconds가 증가하지 않으므로 간격을 지우는 것만으로는 작동하지 않습니다. 시계가 일시 중지되었는지 여부를 결정하는 플래그를 설정합니다.

이 플래그는 pause()를 호출하거나 resume()을 설정할 때 간단히 설정됩니다. 나는 TotalSeconds 증가를 '틱'타임 아웃으로 분리했다. 일시 중지 된 경우에도 계속 실행됩니다 (다시 시작할 때 추적 할 수 있도록).

따라서 틱 기능은 시계가 일시 중지되지 않은 경우에만 시간을 업데이트합니다.

function clock() 
{ 
    var pauseObj = new Object(); 

    var totalSeconds = 0; 
    var isPaused = false; 
    var delay = setInterval(tick, 1000); 

    function pause() 
    { 
     isPaused = true; 
    } 

    function resume() 
    { 
     isPaused = false; 
    } 

    function setTime() 
    { 
     var ctr; 
     $(".icon-play").each(function(){ 
      if($(this).parent().hasClass('hide')) 
       ctr = ($(this).attr('id')).split('_'); 
     }); 

     $("#hour_" + ctr[1]).text(pad(Math.floor(totalSeconds/3600))); 
     $("#min_" + ctr[1]).text(pad(Math.floor((totalSeconds/60)%60))); 
     $("#sec_" + ctr[1]).text(pad(parseInt(totalSeconds%60))); 
    } 

    function tick() 
    { 
     ++totalSeconds; 

     if (!isPaused) 
      setTime(); 
    } 
} 
+0

고마워요. 이걸 곧바로 시험해 보겠습니다. – esandrkwn

0
<html> 
    <head><title>Timer</title> 
    <script> 

    //Evaluate the expression at the specified interval using setInterval() 
    var a = setInterval(function(){disp()},1000); 

    //Write the display() for timer 
    function disp() 
    { 
     var x = new Date(); 

     //locale is used to return the Date object as string 
     x= x.toLocaleTimeString(); 

     //Get the element by ID in disp() 
     document.getElementById("x").innerHTML=x; 
    } 
    function stop() 
    { 
     //clearInterval() is used to pause the timer 
     clearInterval(a); 
    } 
    function start() 
    {  
     //setInterval() is used to resume the timer 
     a=setInterval(function(){disp()},1000); 
    } 

    </script> 
    </head> 
    <body> 
    <p id = "x"></p> 
    <button onclick = "stop()"> Pause </button> 
    <button onclick = "start()"> Resume </button> 
    </body> 
    </html> 
+0

코드에 몇 가지 의견을 추가하십시오. – kvorobiev

관련 문제