실제로 무한 루프를 중지 할 필요가 없습니다. 예를 들어 setImmediate
를 사용 : 당신이 그것을 멈출 때까지 코드의
var immediateId;
function loop() {
console.log('hi');
immediateId = setImmediate(loop);
}
loop();
이 덩어리는 하이 말을 유지합니다.
//stop the loop:
clearImmediate(immediateId);
메모리 부추가 발생하지 않습니다 메모리 소비와 낮은 유지 setImmediate
- 를 사용하는 이유;
- 은
RangeError: Maximum call stack size exceeded
을 던지지 않습니다.
- 성능이 좋습니다. 또한 더
,
나는 쉽게 무한 루프를 관리하기 위해이 모듈을 만든 :
var util = require('util');
var ee = require('events').EventEmitter;
var Forever = function() {
ee.call(this);
this.args = [];
};
util.inherits(Forever, ee);
module.exports = Forever;
Forever.prototype.add = function() {
if ('function' === typeof arguments[0]) {
this.handler = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
if (args.length > 0) {
this.args = args;
}
} else {
this.emit('error', new Error('when using add function, the first argument should be a function'));
return 0;
}
return this;
};
Forever.prototype.run = function() {
var handler = this.handler;
var args = this.args;
var that = this;
this._immediateId = setImmediate(function() {
if (typeof handler === 'function') {
switch (args.length) {
// fast cases
case 0:
handler.call(that);
that.run();
break;
case 1:
handler.call(that, args[0]);
that.run();
break;
case 2:
handler.call(that, args[0], args[1]);
that.run();
break;
// slower
default:
handler.apply(that, args);
that.run();
}
} else {
//no function added
that.emit('error', new Error('no function has been added to Forever'));
}
});
};
Forever.prototype.stop = function() {
if (this._immediateId !== null) {
clearImmediate(this._immediateId);
} else {
this.emit('error', new Error('You cannot stop a loop before it has been started'));
}
};
Forever.prototype.onError = function(errHandler) {
if ('function' === typeof errHandler) {
this.on('error', errHandler);
} else {
this.emit('error', new Error('You should use a function to handle the error'));
}
return this;
};
사용 예 : 그거야
var Forever = require('path/to/this/file');
var f = new Forever();
// function to be runned
function say(content1, content2){
console.log(content1 + content2);
}
//add function to the loop
//the first argument is the function, the rest are its arguments
//chainable api
f.add(say, 'hello', ' world!').run();
//stop it after 5s
setTimeout(function(){
f.stop();
}, 5000);
합니다.
왜 반복 수에 상한값을 넣지 않으십니까? – jbabey