How to implement a “function timeout” in Javascript - not just the 'setTimeout'

后端 未结 5 1374
情歌与酒
情歌与酒 2020-12-16 00:33

How to implement a timeout in Javascript, not the window.timeout but something like session timeout or socket timeout - basically - a

5条回答
  •  感动是毒
    2020-12-16 00:44

    You could execute the code in a web worker. Then you are still able to handle timeout events while the code is running. As soon as the web worker finishes its job you can cancel the timeout. And as soon as the timeout happens you can terminate the web worker.

    execWithTimeout(function() {
        if (Math.random() < 0.5) {
            for(;;) {}
        } else {
            return 12;
        }
    }, 3000, function(err, result) {
        if (err) {
            console.log('Error: ' + err.message);
        } else {
            console.log('Result: ' + result);
        }
    });
    
    function execWithTimeout(code, timeout, callback) {
        var worker = new Worker('data:text/javascript;base64,' + btoa('self.postMessage((' + String(code) + '\n)());'));
        var id = setTimeout(function() {
            worker.terminate();
            callback(new Error('Timeout'));
        }, timeout);
        worker.addEventListener('error', function(e) {
            clearTimeout(id);
            callback(e);
        });
        worker.addEventListener('message', function(e) {
            clearTimeout(id);
            callback(null, e.data);
        });
    }
    

提交回复
热议问题