Node.js setTimeout 不等待

Node.js setTimout not waiting

我已经使用 setTimeout 很长时间了,但是我无法解释忽略等待时间的节点 js 超时。

这里是被指责的代码(在 Node 8.11.3 中):

//Here is the issue
socket.on('GameInput', function (input, state) {
    setTimeout(socket.player.input, 10000, input, state);
});

//The player constructor is pretty standard
const _PLAYER = function(socket, name) {
    //properties
    this.input = function(input, state) {
        //dosomestuff
        io.emit('GameInput', this.name, input, state);
    }
}

我只是在玩家输入上制造一个假延迟(以测试可玩性),无论我写多少毫秒都没有效果。

编辑: 真正的问题是我没有正确重启我的节点服务器...... 好的代码确实是 setTimeout(()=>{socket.player.input(输入, 状态);}, 10000); 我试过了但是没有重启效果不明显-__-

您需要在函数调用中将函数包装在超时中,否则您正在调用函数,而不是在超时结束时将其传递完成。

像这样:

socket.on('GameInput', function (input, state) { setTimeout(function() { socket.player.input(input, state) }, 10000); });