【问题标题】:Maximum call stack size exceeded, trying to make counting up value in my div超出最大调用堆栈大小,试图在我的 div 中计算值
【发布时间】:2021-07-11 12:04:07
【问题描述】:

试图将我的 div 中的 innerText 从 0 更改为 div 中的值。 你能告诉我 - 为什么超出调用堆栈大小,我试图创造条件离开我的递归 - 但它不起作用

const itemsToCount = document.querySelectorAll('.customers'); 


function counter (item) {
    let stopPoint = Number(item.innerText.slice(0,-1));
    let counterNum = 0; 
    function increase () {  
        if (counterNum === stopPoint) {
            item.innerText = `${item}+`
            return; 
        } else {
            setTimeout(() => {
                item.innerText = counterNum; 
                
            }, 100)
            counterNum += 1;
            return increase(); 
        }
        
    }
    increase()
}

Array.from(itemsToCount).forEach(item => {
    counter(item)
})

我的 HTML 看起来像

                 <div class="wrapper">
                      <p class="experience__counter customers">250+</p>
                      <p class="experience__counter customers">20+</p>
                      <p class="experience__counter customers">150+</p>

                    </div>
                  </div>

【问题讨论】:

  • 您能否举例说明如何这些值是如何改变的?它们只是意味着每 10 秒增加一次吗?
  • 您的代码不会像我那样失败。但是,您的逻辑存在根本缺陷 - 代码不会等待 setTimeout 完成,因此在调用 item.innerText = counterNum; 时(每十分之一秒) - counterNum 已经处于该节点的最大值
  • 但是,我强调没有堆栈大小超出错误(也许你的真实计数器有更高的值)
  • 是的,每 10 秒的值应该在我的页面上的 div 中更改一次。当它达到来自 html 的值时,这个“循环”就会停止。
  • 尝试将 counterNum += 1; increase(); 放入 setTimeout 回调中

标签: javascript html settimeout


【解决方案1】:

嘿,根据我的说法,querySelectorAll 返回一个集合,因此您不能像这样更改它的 innerText。你必须使用这个 -- itemsToCount[0] 这里 0 是索引尝试使用这个

【讨论】:

  • 这已经在问题中发布的代码中,Array.from() 所在的位置。
【解决方案2】:

"尝试将 counterNum += 1; increase(); 放在 setTimeout 回调中" 好极了 2 天前

谢谢https://stackoverflow.com/users/10549313/bravo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-24
    • 2015-12-29
    • 2017-12-27
    • 2020-12-06
    • 2012-06-26
    • 2018-02-06
    相关资源
    最近更新 更多