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

查看:41
本文介绍了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");
    }
}

但是,当过滤器需要很长时间才能加载时,我收到未捕获的范围错误:超出最大调用堆栈大小(...)"

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(),并且
  • 确保将使用正确的 this 值调用该函数(.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天全站免登陆