타이머(Timer), 이벤트(Event), 리스너(Listner) 콜백 사용 예제
1. Timer를 이용한 작업 스케쥴링(setTimer)
setTimer : 1회성 콜백 함수의 실행
사용법 : timerID = setTimer(callback, delayMilliSeconds, [args]);
clearTimer : 타이머 취소
사용법 : clearTimer(timerID);
function simpleTimeout(consoleTimer) { console.timeEnd(consoleTimer); } console.time("twoSecond"); setTimeout(simpleTimeout, 2000, "twoSecond"); console.time("oneSecond"); setTimeout(simpleTimeout, 1000, "oneSecond"); console.time("fiveSecond"); setTimeout(simpleTimeout, 5000, "fiveSecond"); console.time("50MilliSecond"); setTimeout(simpleTimeout, 50, "50MilliSecond");
C:\newWorks\nodejs>node simple_timer.js
50MilliSecond: 51.079ms
oneSecond: 1006.651ms
twoSecond: 2002.343ms
fiveSecond: 5000.469ms
2. Timer를 이용한 주기적 작업 스케쥴링(setInterval)
setInterval: 주기적 콜백 함수의 실행
사용법 : timerID = setInterval(callback, delayMilliSeconds, [args]);
clearInterval : 타이머 취소
사용법 : clearInterval(timerID);
var x=0, y=0, z=0; var idX, idY, idZ; function displayValues() { console.log("X=%d; Y=%d; Z=%d", x, y, z); } function updateX() { x += 1; } function updateY() { y += 1; } function updateZ() { z +=1; displayValues(); } function clearTimerAll() { clearInterval(idX); clearInterval(idY); clearInterval(idZ); } idX = setInterval(updateX, 500); idY = setInterval(updateY, 1000); idZ = setInterval(updateZ, 2000); setTimeout(clearTimerAll, 10000);
C:\newWorks\nodejs>node simple_interval.js
X=3; Y=1; Z=1
X=7; Y=3; Z=2
X=11; Y=5; Z=3
X=15; Y=7; Z=4
3. Timer를 이용한 즉시 실행후 주기적 작업 스케쥴링(setImmediate)
setImmediate: 호출과 함께 콜백 함수를 실행후 주기적 실행
사용법 : timerID = setImmediate(callback, delayMilliSeconds, [args]);
clearImmediate : 타이머 취소
사용법 : clearImmediate(timerID);
4. Timer의 보류/복구(unref, ref)
timerID.unref : set 함수를 이용해 setTimeout / setInterval을 이용해 타이머를 설정했을 경우 유일하게 하나의 타이머만 남았을 경우 참조를 해제 함으로써 콜백 함수의 실행을 보류 시킬 수 있다.
timerID.ref : unref에 의해서 참조 해제된 콜백 함수를 재개하도록 한다.
5. EventEmitter객체를 이용한 이벤트 발생
emitter.emit(eventName, [args])
제공된 전달 인자를 포함한 이벤트를 유발 시킨다.
자바스크립트 객체에 직접 이벤트를 추가 하려면 객체 초기화시 events.EventEmitter.call(this)를 호출해 EventEmitter기능을 상속받도록 하고 객체의 프로토타입에 events.EventEmitter.prototype을 추가해야 한다.
function MyObj()
{
Events.EventEmitter.call(this);
}
MyObj.prototype.__proto__ = events.EventEmitter.prototype;
이렇게 해야 다음과 같이 객체 인스턴스에서 직접 이벤트를 발생 시킬 수 있다.
var myObj = new MyObj();
myObj.emit("someEvent");
var events = requires('events'); var emitter = new events.EventEmitter(); emitter.emit("simpleEvent");
6. 이벤트 리스너(Event Listner) 추가/삭제
객체에 이벤트 리스너(Listner)를 추가/제거 할 수 있다.
이벤트 추가
addListner(eventName, callback); //객체리스너에 콜백 함수 추가
object.on(eventName, callback); //객체 리스너에 콜백 함수 추가
object.once(eventName, callback); //1회 실행용 리스너 콜백 함수 추가
이벤트 제거
listeners(eventName); //eventName 이벤트에 추가된 리스너 콜백함수 배열 반환
.setMaxListners(n); //EventEmitter에 n보다 많은 리스너가 추가된 경우 경고 한다.
.removeListner(eventName, callback); EventEmitter의 EventName 이벤트에 추가된 callback 함수를 제거
var events = require("events"); function Account() { this.balance = 0; events.EventEmitter.call(this); this.deposit = function(amount) { this.balance += amount; console.log("occured event in deposit") this.emit('balanceChanged'); // 변경되었다고 이벤트를 발생 시킨다. } this.withdraw = function(amount) { this.balance -= amount; console.log("occured event in withdraw") this.emit('balanceChanged'); } } Account.prototype.__proto__ = events.EventEmitter.prototype; function displayBalance() { console.log("balance = %d in displayBalance", this.balance) console.log("Account balance : $%d", this.balance); } function checkOverdraw() { if (this.balance<0) { console.log("Account overdrawn!!!"); } } function checkGoal(acc, goal) { if (acc.balance > goal) { console.log("Goal Achived!!!"); } } var account = new Account(); account.on("balanceChanged", displayBalance); account.on("balanceChanged", checkOverdraw); account.on("balanceChanged", function() {checkGoal(this, 1000)}); account.deposit(220); account.deposit(320); account.deposit(600); account.withdraw(1400);
C:\newWorks\nodejs>node emitter_listner.js
occured event in deposit
balance = 220 in displayBalance
Account balance : $220
occured event in deposit
balance = 540 in displayBalance
Account balance : $540
occured event in deposit
balance = 1140 in displayBalance
Account balance : $1140
Goal Achived!!!
occured event in withdraw
balance = -260 in displayBalance
Account balance : $-260
Account overdrawn!!!
참고 : <Node.js, MongoDB와 AngularJS를 이용한 웹 개발, 에이콘 출판>
'프로그래밍 > JavaScript' 카테고리의 다른 글
[Node.js] 콘솔(console) 모듈 정리 (0) | 2017.08.04 |
---|---|
[Node.js] 입문...(설치 및 웹서버 만들고 운영해보기) (0) | 2017.07.29 |