简体   繁体   English

在JavaScript中一定时间后如何停止executinf函数

[英]How to stop executinf function after certain amount of time in JavaScript

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. 我是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. 但是我需要停止运行某些功能(这里是longWorking),该功能可以执行几秒钟或那么多时间。 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. 但是我不知道要用JS实现。 I thought in this way (above)... But it doesn't work. 我是这样想的(上面)...但是没有用。 Can someone help me? 有人能帮我吗?

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. 因此,该函数每秒运行一次,如果花费超过6秒钟,它将停止。 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. 因此,基本上,您可以将工作负载放在doSomething()函数中,让它每秒工作一次,如果花费太长时间则将其停止。 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? 这是您要找的东西吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM