NodeJS在请求结束时终止setTimeout()

时间:2017-09-29 18:12:24

标签: javascript node.js express

在下面的代码中,setTimeout()在客户端关闭请求后继续运行。我该如何阻止它?

function doSomething(callback){
    console.log('Doing something...');
    callback();
}

app.get('/', (req, res) => {

    function waitTilDone(){
        setTimeout(function(){
            doSomething(waitTilDone);
        }, 2000);
    }

    doSomething(waitTilDone)

});

1 个答案:

答案 0 :(得分:2)

Express Request是节点IncomingMessage的增强版,其中包含endabortedapp.get('/', (req, res) => { var timer = 0; req.on('aborted', function() { if (timer) { clearTimeout(timer); } }); function waitTilDone(){ timer = setTimeout(function(){ doSomething(waitTilDone); }, 2000); } doSomething(waitTilDone) }); 个事件。挂钩到最合适的事件并清除超时。例如:

{{1}}