Killing a JavaScript function which runs infinite

前端 未结 6 525
难免孤独
难免孤独 2021-01-19 00:04

As an example

var runInfinite = function(){
    while(1)
    {
       // Do stuff;
    }
};

setTimeout(runInfinite, 0);

Is it possible to

6条回答
  •  天命终不由人
    2021-01-19 00:31

    I admit this is not exactly the same, but, there are the Javascript generators and Javascript iterators in ECMA-262. If you can replace your function with a generator function, then, you can implement the breakable feature easily.

    function execWithTimeout(iter, timeout = 100) {
        const limit = Date.now() + timeout
        for (const output of iter) {
            console.log(output)
            if (Date.now() > limit) throw(new Error("Timeout reached"))
        }
    }
    
    let runInfinite = function * () {
        let i = 0
        while (1) {
            yield i++
        }
    }
    
    execWithTimeout(runInfinite())

提交回复
热议问题