其實,你不需要停止無限循環。使用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 2012-07-13 18:45:12