gpt4 book ai didi

javascript - 如何在 JavaScript 中从外部停止递归循环函数?

转载 作者:行者123 更新时间:2023-12-03 01:29:56 24 4
gpt4 key购买 nike

在我的应用程序中,我允许用户启动循环递归函数的多个实例。目前,每个函数将永远持续下去,我需要一种方法来显式结束每个函数。考虑到这一点,我想我需要保留一个正在运行的进程数组,并为每个进程存储一个唯一的 id,并将 isRunning 变量与其关联,但我无法完全理解如何实现这一点。

每当用户向我的 API 发出 POST 时,服务器端的此函数就会从前端调用,并且会继续以随机间隔调用自身。

function scrapeAtRandomInterval(id, search_terms, category, location, min, max) {

// Not currently using the id param as I don't need it for anything on the server side but thought it might come in handy to solve this issue.

scrape(location, category, search_terms, min, max);

var rand = randomIntBetweenBounds(0, 3600000 / 3);
setTimeout(function() {
scrapeAtRandomInterval(id, search_terms, category, location, min, max);
}, rand);
}

当用户发出 DELETE 请求时,我需要一种方法来停止与调用该函数的 POST 关联的函数调用。再次,我想象通过引用一个对象数组,每个对象都带有 id 和 bool 标志,然后也许在函数内部我可以添加一个检查是否正在运行?

最佳答案

I imagine by referencing an array of objects each with the id ...

搜索数组的平均时间为O(n/2),使用对象作为哈希表的时间为O(1),因此速度要快得多,因此使用数组可以工作,但速度很慢(对于许多正在运行的进程而言)。

... and a bool flag and then maybe inside the function I could add a check if isRunning?

或者更简单,您只需将计时器存储在 id 下并在需要时取消它,因为您需要一个对象来存储基于进程 id 的计时器 id:

const timers = {};

然后在设置新的超时时存储其 id:

timers[id] = setTimeout(...);

然后要清除它,只需执行以下操作:

clearTimeout(timers[id]);
delete timers[id]; // allow the engine to optimize the hashtable

关于javascript - 如何在 JavaScript 中从外部停止递归循环函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51350157/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com