简体   繁体   English

可以在闭包中调用setTimeout导致内存泄漏吗?

[英]Can calling setTimeout in a closure cause a memory leak?

I have a third-party JavaScript object on which I'm calling a method “search” and passing in a search query string along with a function to execute once the search is complete. 我有一个第三方JavaScript对象,在该对象上我将其称为“搜索”方法,并传递搜索查询字符串以及在搜索完成后要执行的函数。 This third-party object then goes away and attempts to retrieve data from a service. 然后,该第三方对象消失并尝试从服务中检索数据。 If the service call fails to return within 10 seconds, the third-party object logs a timeout error but unfortunately doesn't execute the callback function with a status of “Timeout” or something else applicable. 如果服务调用未能在10秒钟内返回,则第三方对象会记录超时错误,但不幸的是不会以“超时”或其他适用的状态执行回调函数。

In order to have the callback execute when there has been a timeout, I've wrapped the third-party object call as per the code below: 为了使超时时执行回调,我按照下面的代码包装了第三方对象调用:

var SEARCH_TIMEOUT_MILLISECONDS = 10500;

var thirdPartyObject = ... // Global variable

function search(searchTerm, onCompleteCallback) {

    var searchTimeoutHandler = setTimeout(function () {
        onCompleteCallback(null, 'TIMEOUT');
    }, SEARCH_TIMEOUT_MILLISECONDS);

    thirdPartyObject.search({
        searchTerm: searchTerm,
        onComplete: function (searchResponse, status) {

            clearTimeout(searchTimeoutHandler);

            onCompleteCallback(searchResponse, status);
        }
    });
}

Where a closure is being created, if this function was called hundreds of times (some concurrently), would there be any memory issues in the scenarios of the setTimeout function either being or not being called? 在创建闭包的地方,如果该函数被调用了数百次(并发),那么在setTimeout函数被调用或不被调用的情况下,是否会出现任何内存问题?

No, there shouldn't be any memory leaks. 不,不应该有任何内存泄漏。 There are only two scenarios as far as the timeout is concerned: 就超时而言,只有两种情况:

  • Timeout handler is called, after which it is garbage collected. 调用超时处理程序,之后将其垃圾回收。
  • Timeout is cleared, after which it is also garbage collected. 清除超时,之后也将对其进行垃圾回收。

However, if you have multiple searches being done hundreds of times, those timeout handlers can pile up, but they will eventually be cleared (after taking at most n * SEARCH_TIMEOUT_MILLISECONDS , where n is the number of times search has been called which is also the number of instances of timeout handlers you will have). 但是,如果您执行了数百次多次搜索,那么这些超时处理程序可能会堆积起来,但最终将被清除(最多执行n * SEARCH_TIMEOUT_MILLISECONDS ,其中n是已调用search的次数,这也是您将拥有的超时处理程序的实例数)。 So there is no memory-leak per se, but you can have things stacking up. 因此,本质上没有内存泄漏,但是您可以堆积很多东西。 You might have to tune the SEARCH_TIMEOUT_MILLISECONDS variable so that you don't have things stacking up. 您可能需要调整SEARCH_TIMEOUT_MILLISECONDS变量,以免发生任何事情。 You can also look at memory usage on Chrome Developer Tools to see how much memory is being used up. 您还可以在Chrome开发者工具上查看内存使用情况,以查看已用完多少内存。

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

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