Killing a JavaScript function which runs infinite

前端 未结 6 473
难免孤独
难免孤独 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:39

    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.

提交回复
热议问题