- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在我的应用程序中,我允许用户启动循环递归函数的多个实例。目前,每个函数将永远持续下去,我需要一种方法来显式结束每个函数。考虑到这一点,我想我需要保留一个正在运行的进程数组,并为每个进程存储一个唯一的 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/
我是一名优秀的程序员,十分优秀!