SetTimeout递归函数(Javascript)超出最大调用堆栈大小 [英] Maximum call stack size exceeded on SetTimeout recursive function (Javascript)

查看:117
本文介绍了SetTimeout递归函数(Javascript)超出最大调用堆栈大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个递归的SetTimeout函数,在加载过滤器后点击我页面上的过滤器(它们是通过Ajax加载的,所以在页面加载时不能立即使用)。

I have a recursive SetTimeout function that clicks a filter on my page after the filters have loaded (they're loaded through Ajax, so not available immediately on page load).

$scope.clickFilter = function () {
    var filter = $('.filter-item')
        .find('input[value="' + $scope.activeFilter + '"]');

    if (filter.length < 1) {
        setTimeout($scope.clickFilter(), 1000);
    } else {
        $(filter).trigger("click");
    }
}

但是,过滤器需要很长时间才能加载,我得到Uncaught RangeError:超出最大调用堆栈大小(...)

However, when the filters take a long time to load, I get "Uncaught RangeError: Maximum call stack size exceeded(…)"

如何防止这种情况并确保它一直运行直到完成?

How do I prevent this and make sure it runs until completion?

推荐答案

问题在于:

  setTimeout($scope.clickFilter(), 1000); 

在函数引用之后放置()您希望函数在代码中的那一点立即调用。您可能需要的是:

Putting () after the function reference means that you want the function to be called, immediately, at that point in the code. What you probably want instead is something like:

  setTimeout($scope.clickFilter.bind($scope), 1000);

这将


  • 根据需要将函数引用传递给 setTimeout(),并且

  • 确保将使用正确值( .bind()部分的内容)

  • pass a function reference to setTimeout(), as is required, and
  • ensure that the function will be invoked with the proper this value (what the .bind() part does)

一旦你开始工作,递归一词就不合适了。是的,当函数在计时器到期后安排调用时,该函数会引用自身,但它并不直接调用自身;它要求其他东西(计时器机制)稍后再调用它。

Once you get it working, the term "recursive" isn't really appropriate. Yes, the function is referencing itself when it arranges for the call after the timer expires, but it's not directly calling itself; it's asking something else (the timer mechanism) to call it later.

这篇关于SetTimeout递归函数(Javascript)超出最大调用堆栈大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆