admin管理员组

文章数量:1434949

I have this code:

function toStop(){
  while(true){}
}
toStop();

Now, how can I stop this? Or how can I kill the current thread if this function call is somewhere in the setInterval running thread? Example:

var id = setInterval(function(){
  toStop();
}, 1000);

//stop thread/timer with id here.

clearInterval doesn't work because it waits until the function call ends.

Thanks!

I have this code:

function toStop(){
  while(true){}
}
toStop();

Now, how can I stop this? Or how can I kill the current thread if this function call is somewhere in the setInterval running thread? Example:

var id = setInterval(function(){
  toStop();
}, 1000);

//stop thread/timer with id here.

clearInterval doesn't work because it waits until the function call ends.

Thanks!

Share Improve this question edited May 27, 2017 at 22:48 Badacadabra 8,5357 gold badges31 silver badges54 bronze badges asked Mar 12, 2015 at 20:43 Bogdan BBogdan B 751 silver badge6 bronze badges 17
  • 2 I believe the best you can do is have a global flag that allows you to break out of your loop. – Phylogenesis Commented Mar 12, 2015 at 20:46
  • 4 JS is single threaded. When you execute that infinite loop, nothing else can execute until that function pletes. – TheDude Commented Mar 12, 2015 at 20:48
  • 1 I agree with Austin, while this question may be similar to the other in title, in content they ask very different questions. – Travis J Commented Mar 12, 2015 at 21:10
  • 1 @TravisJ 5 seconds is pretty normal if you're loading a video or a large image from a remote (or slow) server. – Austin Mullins Commented Mar 12, 2015 at 21:14
  • 1 @TravisJ How is it different? The OP creates an infinite loop and asks if he can stop it afterwards, programmatically. That's just not possible, since the main thread will be busy forever. If the OP did ask how he could process some tasks without endlessly blocking the main thread, that would have been a different question. – plalx Commented Mar 12, 2015 at 21:59
 |  Show 12 more ments

3 Answers 3

Reset to default 2

"Can I stop the execution of a function from outside that function?"

No, you can't programmatically.

JavaScript is single-threaded and if you run a piece of code that makes it infinitely busy, such as while(true);, then nothing else will ever be able to execute.

Calling such a piece of code within setTimeout or setInterval will have the same result, since the callback of these gets executed in the only thread we have as well.

However, you can create a timed recurring execution using setInterval or setTimeout, which can be stopped.

var timerId = setInterval(function () {
    //Process an iteration of the loop in here

    //If you cause an infinite loop in here, you will have the same issue

}, 50);

//stop the timer after ~3 seconds
setTimeout(clearInterval.bind(null, timerId), 3000);

Notes:

  • 4 is the lowest interval that could be honored as specified in the SPEC.
  • setInterval will stack if the callback takes more time to execute than the specified interval. For that reason I never use setInterval and always use setTimeout.
  • Timer intervals are not guaranteed to be accurate

e.g. with setTimeout

var stopProcessing = startProcessing();

//Stop processing after ~3 seconds
setTimeout(stopProcessing, 3000);

function startProcessing() {
    var timerId;

    !function process() {
        //Do some processing

        //Continue processing in ~50 ms
        timerId = setTimeout(process, 50);
    }();

    return function () { clearTimeout(timerId); }
}

Instead of an infinite loop, just use an if statement and wrap it in an interval:

var shouldContinue = true;
var interval = 0;

function toStop() {
    if (interval == 0) {
        interval = setInterval(function() {
            if(shouldContinue) {
                ...
            }
            else {
              clearInterval(interval);
              interval = 0;
            }
        }, 200); // Or whatever interval makes sense
    }
}

toStop();

// ...

shouldContinue = false;

See this principle in action here.

No, you can't programmatically, as @plalx said but you could try this: declaring a binding outside and check on that to continue or stop the loop:

let letMeGoOut;
function toStop(){
    while(letMeGoOut != false)
}
toStop();

Here, I've created a function on mouseover that triggers a loop changing the opacity of the h1. It goes on till the mouse cursor moves out and is over something else in the page.

Here is the example: https://codepen.io/Mau-Di-Bert/pen/VqrRxE

本文标签: javascriptCan I stop the execution of a function from outside that functionStack Overflow