2014-02-15 1 views
1

특정 시간 이후에 일부 이벤트를 트리거하려고합니다. 타이머는 일시 중지되어야합니다. http://jsfiddle.net/xsH8v/js : 일시 중지/다시 시작 후 타이밍 이벤트 트리거

문제는 어떻게 내가 document.ready에 넣어이

if (Clock.totalSeconds >= givenTime){ 
    alert('time is up!'); 
    } 

를 실행할 수 있다는 것입니다 : 다음은 코드입니다. 그러나 시간이 다되면 해고되지 않습니다. 문제는 함수가 전혀 호출되지 않는다는 것입니다. 그렇다면 어떻게 작동시킬 수 있습니까?

답변

1

귀하의 방법이 작동하지 않는 때문에 문이 한 번만 평가되는 경우; 문서로드시. 이를 해결하려면 totalSeconds가 업데이트 될 때마다 점검되는 콜백을 추가해야합니다.

여기 내 해결책이 있습니다. fiddle here

당신과 같이, Clock.at(time, callback)를 사용하여 기능을 추가 할 수

Clock.at (10, 함수() {/ * 10초 * /} 통과); 문이 totalSecondssetInterval에 의해 업데이트 될 때마다 호출 할 필요가있는 경우

var Clock = { 
    totalSeconds: 0, 

    handlers: [], 

    start: function() { 
     var self = this; 

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

      sec = parseInt(self.totalSeconds % 60) 
      min = Math.floor(self.totalSeconds/60 % 60) 
      hour = Math.floor(self.totalSeconds/3600) 

      $("#hour").text(hour); 
      $("#min").text(min); 
      $("#sec").text(sec); 

      // Fire each expired handlers 
      self.handlers = self.handlers.filter(function(handler) { 

       if (self.totalSeconds >= handler.time) { 
        // Fire the handler then remove it 
        handler.func(); 
        return false; 
       } 

       return true; 
      }) 

     }, 1000); 
    }, 

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

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

    at: function(time, handler) { 

     // Handle expired handlers 
     if (this.totalSeconds >= time) handler(); 

     // Add the handler to the queue 
     this.handlers.push({ 
      time: time, 
      func: handler, 
     }); 
    } 
}; 
1

당신은 후 exucted됩니다 Clock.start()-maxTime는 주어진 시간에 여기

var givenTime = 5; 
//maxTime is call back function which is executed after extend giventTime 
Clock.start(maxTime, givenTime); 

function maxTime(){ 
    //do stuff after extend maximum time. 
} 

//here is your call back function is invoked when `givenTime` time is extended 
// inside the `start function` 
//after that every second the call back function is executed. 

if(self.totalSeconds >= givenTime){ 
    callBack(); 
} 

입니다을 확장 할 콜백 함수를 전달할 수 있습니다 전체 DEMO

한 번만를 TimeUp 코드를 실행 할합니다. 당신은 VAR을 제거하여 귀하의 경우에는

, 변수 giventTime 글로벌 바랍니다

if(self.totalSeconds == givenTime){ 

DEMO2

UPDATE처럼 start() 함수 내에서 codnition을 설정, 그리고 외부에서 maxTime() 기능을 배치 할 수 있습니다 the $(document).ready

$(document).ready(function() {...}); 

function maxTime(){ 
     alert('time up'); 
    } 

그리고

if (!this.interval) this.start(maxTime, givenTime) 
처럼 resume() 기능에 start() 기능이 상대적 매개 변수를 전달

DEMO3

+0

당신 솔루션이 첫 번째 호출 후 콜백마다 두 번째를 호출하고, 하나의 콜백을 허용합니다. 나는 이것이 OP를 위해 바람직하지 않다고 가정합니다. – Indy

+0

@ 아이디 업데이트 된 답변으로 demo2를 보시기 바랍니다. –

+0

추가 질문 :'resume' 함수에서 인수는 비어 있어야합니다. if (! this.interval) this.시작(); ' – cqcn1991

0

그래서 그것은 setInterval 함수 안에 넣어. 주어진 시간을 인수로 시작 함수에 전달할 수 있습니다. updated fiddle

$(document).ready(function() { 
    Clock.start(5); 
    $('#pauseButton').click(function() { Clock.pause(); }); 
    $('#resumeButton').click(function() { Clock.resume(); }); 

}); 

var Clock = { 
    totalSeconds: 0, 

    start: function (maxTime) { 
     var self = this; 

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

      sec = parseInt(self.totalSeconds % 60) 
      min = Math.floor(self.totalSeconds/60 % 60) 
      hour = Math.floor(self.totalSeconds/3600) 

      $("#hour").text(hour); 
      $("#min").text(min); 
      $("#sec").text(sec); 

      // Check condition after each increment in Clock.totalSeconds 
      if (Clock.totalSeconds >= maxTime) { 
       Clock.pause(); 
       alert('time is up!'); 
      } 
     }, 1000); 
    }, 

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

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

당신은이 첫 번째 호출 후에 솔루션이 1 초마다 콜백을 호출합니다. 이는 OP에 대해 바람직하지 않은 동작이라고 생각합니다. – Indy

+0

솔루션을 업데이트했습니다. 이제이 첫 번째 호출 후에 매 초마다 콜백을 호출하지 않습니다. – rkb