循环内的socket.io不起作用

我试图在循环内发射事件。 但是,只是启动第一个事件(开始)和一次。

控制台中的行为必须是:发出事件开始发出事件结束b发出事件开始发出事件结束

又一次

发射事件开始发射事件完成b发射事件开始发射事件完成

然而,它的行为方式是:

发射事件开始b

又一次

一个b

为什么事件只发出一次?

var server = require('http').createServer(); var io = require('socket.io')(server); var sleep = require('sleep'); io.on('connection', function(socket){ socket.on('disconnect', function(){}); }); server.listen(3000); function B() { this.bundles = ['a', 'b']; this.currentPosition = 0; this.run = function() { var bundle = this.bundles[this.currentPosition]; console.log(bundle); io.emit('start', { 'bundle': bundle }); io.emit('finish', { 'bundle': bundle }); ++this.currentPosition; if (this.bundles[this.currentPosition] === undefined) { this.currentPosition = 0; } sleep.sleep(2); this.run(); } } //wait to start server setTimeout(function(){ var b = new B(); b.run(); }, 6000); 

尝试将其更改为setInterval

http://codepen.io/Chevex/pen/zGdQXQ

  this.run = function() { var bundle = this.bundles[this.currentPosition]; console.log(bundle); io.emit('start', { 'bundle': bundle }); io.emit('finish', { 'bundle': bundle }); ++this.currentPosition; if (this.bundles[this.currentPosition] === undefined) { this.currentPosition = 0; } } setInterval(this.run.bind(this), 2000); 

间隔将每2秒运行一次,不会泛滥您的调用堆栈。

无论何时从另一个函数调用函数,都会构build一个调用堆栈。

 function foo() { bar(); } function bar() { console.log('end of stack, returning'); } foo(); 

上面的代码会像这样构build一个堆栈:

 -> event loop -> foo -> bar -> console.log 

然后当函数开始返回时,它们一个接一个地从堆栈中popup。 这意味着当你从内部调用一个函数的时候,如果recursion调用从不停止的话,你肯定会耗尽调用栈。

 function foo() { foo(); } foo(); 

这将导致一个丑陋的调用堆栈,将运行你的记忆干燥。

 -> event loop -> foo -> foo -> foo -> foo -> foo -> etc... 

你可以看到JavaScript引擎甚至试图检测到这种情况,并抛出一个exception。 如果recursion栈更复杂,引擎并不总是捕获这些。 最好避免它,坚持setInterval

通过使用setInterval你注册一个函数与节点,并告诉它每次发射一定的毫秒数。 这样可以节省调用堆栈,因为函数被触发,返回,然后当节点事件循环检测到再次经过n毫秒时再次启动。 没有无限的调用堆栈,将导致…

…堆栈溢出

PS – 现在你明白这个网站自己的标志。 这是一个调用堆栈:)