As an example
var runInfinite = function(){
while(1)
{
// Do stuff;
}
};
setTimeout(runInfinite, 0);
Is it possible to break this runInfinite function form running infinite? I mean is it possible to kill this function from another function without using a flag or return statement?
An infinite loop will run forever, but the program can be terminated with the break keyword.
Using return to exit a function in javascript Using return is the easiest way to exit a function. You can use return by itself or even return a value.
The answer is no. Since JavaScript is single-threaded ( unless you are using some less common implementation which I doubt ) nothing can break a loop ( or any other block of code ) from outside.
There is no direct way to "kill" a running javascript function.
Possible workaround, although you need to replace the while(1)
loop:
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
I know using eval()
is considered to be bad practice, however the idea should be clear. The function calls itself (not recursive, therefore the setTimeout()
) using the toCall
variable. Once this variable is unset, you kill it from outside.
You could wrap these variables and functions in a class so you can implement your "kill" function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With