Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Killing a JavaScript function which runs infinite

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?

like image 365
Somnath Avatar asked Feb 14 '13 08:02

Somnath


People also ask

How do I stop an infinite loop in JavaScript?

An infinite loop will run forever, but the program can be terminated with the break keyword.

How do you end a JavaScript function?

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.


2 Answers

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.

like image 136
freakish Avatar answered Oct 06 '22 00:10

freakish


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.

like image 27
Uooo Avatar answered Oct 05 '22 23:10

Uooo