레이블이 Prototype인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Prototype인 게시물을 표시합니다. 모든 게시물 표시

2006년 5월 31일 수요일

Prototype에서 PeriodicalExecuter 클래스를 이용한 Timer 설정

요약
PeriodicalExecuter의 목적은 특정 시간마다 반복적인 동작을 수행하기 위해서 사용됩니다.

문법
var executer = new PeriodicalExecuter(callback function, interval time);
파라미터
callback function - 일정간격마다 호출될 function을 인자로 받습니다.
interval time - 반복적인 동작을 수행할 시간 간격을 초단위로 받습니다.
코드

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
   initialize: function(callback, frequency) {
       this.callback = callback;
       this.frequency = frequency;
       this.currentlyExecuting = false;
       this.registerCallback();
   },

   //setInterval 메소드를 사용하여 특정 시간마다 onTimerEvent 메소드가
   //호출되도록 합니다.
   registerCallback: function() {
       setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
   },

   //currentlyExecuting가 true인 경우 callback 메소드를 수행합니다.
   onTimerEvent: function() {
       if (!this.currentlyExecuting) {
           try {
               this.currentlyExecuting = true;
               this.callback();
           } finally {
               this.currentlyExecuting = false;
           }
       }
   }
}

동작원리
동작 자체는 단순합니다. setInterval메소드에 자기 자신의 onTimerEvent가 호출되도록 설정한 후  PeriodicalExecuter로 감싼 후, 특정 시간마다 onTimerEvent가 호출될 때 PeriodicalExecuter에 등록되어 있는 callback을 실행합니다. 내부에 실행여부를 결정하는 flag(currentlyExecuting)을 가지고 있습니다.