1
function avoidAfterTime() {
var startTime = new Date().getTime();
var interval = setInterval(function () {
    if (new Date().getTime() - startTime > 3000) {
        clearInterval(interval);
        console.log("more than 2 sec")
        return;
    }
    longWorking();
}, 2000);
}

avoidAfterTime();

function longWorking(){
    var t;
    for (i = 0; i < 1e10; i++) t = i;
    console.log(t);
}    

Hello. I am very new to JS. But I need to stop running some function (here it is longWorking) which can be executed for few seconds or for so much time. And I want to abort the function in case of it takes too long. I guess I know how to make it using, for example, threads in some other programming language. But I have no idea about making it in JS. I thought in this way (above)... But it doesn't work. Can someone help me?

Ben
  • 13
  • 4
  • It cannot. JS is a single thread language and nothing will execute till `for (i = 0; i < 1e10; i++)` ends. Only way is to check inside loop. – Rajesh Jan 27 '16 at 14:04
  • Possible duplicate of [How to terminate the script in Javascript](http://stackoverflow.com/questions/550574/how-to-terminate-the-script-in-javascript) – Pavel Pája Halbich Jan 27 '16 at 14:04
  • 1
    It's so sad. I have almost understood that. Thanks. – Ben Jan 27 '16 at 14:12

1 Answers1

0

hmm, I drafted this example. So it's a function that runs every second and if it takes more than 6 seconds it will stop. So basically you can put your work load in the doSomething() function and let it work every second and stop it if it takes too long. Or you can stop it based on a value. It depends on what do you want to do with it. I used the module pattern to isolate the logic and the variables. So you can encapsulate your logic in a module like way.

(function() {
    'use strict';
    let timing = 0;

    const interval = setInterval(doSomething, 1000);

    function doSomething() {
        timing++;

        if (timing > 5) {
            clearInterval(interval);
        }

        console.log('working');
    }
})();

Is this something you are looking for?

Andrei CACIO
  • 2,101
  • 15
  • 28