Actually, you don't need to stop a infinite loop. use setImmediate
for instance:
var immediateId;
function loop () {
console.log('hi');
immediateId = setImmediate(loop);
}
loop();
This chunk of code will keep saying hi, until you stop it.
//stop the loop:
clearImmediate(immediateId);
why using setImmediate
- the Memory comsumption kept low, will not cause memory leek;
- will not throw a
RangeError: Maximum call stack size exceeded
;
- the performance is good;
Further more,
I created this module for easily managing infinite loop:
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;
};
example usage:
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);
That's it.
break
out of the loop. You are trying to find a solution to a halting problem. – Vindicable