文档库 最新最全的文档下载
当前位置:文档库 › 【IT专家】在setTimeout调用期间超过最大调用堆栈大小

【IT专家】在setTimeout调用期间超过最大调用堆栈大小

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

在setTimeout 调用期间超过最大调用堆栈大小

在setTimeout 调用期间超过最大调用堆栈大小[英]Maximum Call Stack Size Exceeded During a setTimeout Call I’m trying to call my function every 4 seconds so it will increment a number live. For some reason I keep getting errors. Here’s my code:

我试图每4 秒调用一次我的函数,因此它会增加一个数字。出于某种原因,我不

断收到错误。这是我的代码:

html head title Recycle Counter /title script type=“text/javascript”function rand(from, to) return Math.floor(Math.random() * (to - from + 1) + from); // Generates random number var num = rand(10000, 100000); function getNum() // Gets triggered by page load so innerHTML works document.getElementById(‘counter’).innerHTML = num + 7; setTimeOut(getNum(), 4000); /script /head body onload=“getNum()”div id=“counter”/div /body /html 35

Inside getNum, you’re directly invoking the getNum function, causing the stack to exhaust. Replace the function call getNum() with the function reference getNum:

在getNum 中,你直接调用getNum 函数,导致堆栈耗尽。用函数引用getNum 替

换函数调用getNum():

function getNum() // Gets triggered by page load so innerHTML works num += 7; // Increase and assign variable document.getElementById(‘counter’).innerHTML= num; setTimeout(getNum, 4000); // -- The correct way Link to documentation of setTimeout.

链接到setTimeout 的文档。

8

The problem is your call to setTimeout is invoking getNum instead of scheduling it for execution. This leads to infinite recursion and a stack overflow. Try the following instead 问题是你调用setTimeout 正在调用getNum 而不是调度它来执行。这导致无限递

归和堆栈溢出。请尝试以下方法

setTimeout(getNum, 4000); 1

相关文档