Killing a JavaScript function that works endlessly

As an example

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

setTimeout(runInfinite, 0);

Is it possible to break this RunInfinite function, which works endlessly? I mean, is it possible to kill this function from another function without using the flag or the return statement?

+5
source share
6 answers

The answer is no. Since JavaScript is single-threaded (unless you use some less common implementation that I doubt) nothing can break the loop (or any other block of code) from the outside.

+5
source

There is no direct way to "kill" a running javascript function.

A possible workaround though you need to replace the loop while(1):

var i = 0; // for testing purposes

var toCall = "runInfinite()";
function runInfinite(){
    // do stuff
    console.log(i++);
    setTimeout(function(){ eval(toCall); }, 100); // or whatever timeout you want
}

setTimeout(function(){ eval(toCall); }, 0); // start the function
setTimeout(function(){ toCall = ""; }, 5000); // "kill" the function

, eval() , . ( , setTimeout()), toCall. , .

, "kill".

+2

.

AFAIK, while (1) - . , , Chrome ctrl+shift+i typing while(1){} - , -javascript .

, node.js, . - node.js /, . .

+1

, . , , . while(1), , , , ​​ ,

+1

return , .

In your case, you can try so that your function is completed in a try / catch block , you can find out when your function is infinite, based on which you can stop its current execution.

0
source

I admit that this is not quite the same, but ECMA-262 has Javascript generators and Javascript iterators. If you can replace your function with a generator function, then you can easily implement this function.

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())
Run codeHide result

0
source

All Articles