[英]Too much recursion on simple JS slider
I am trying to build a simple slider by changing the background image, but i am not sure why I am getting an error that says too much recursion. 我正在尝试通过更改背景图片来构建一个简单的滑块,但是我不确定为什么会收到错误消息,该错误表明递归过多。
document.addEventListener("DOMContentLoaded", function(event) {
let headerImages = [];
let header = document.querySelector('.header');
let i = 0;
let time = 3000;
headerImages[0] = 'img/header1.jpg';
headerImages[1] = 'img/header2.jpg';
function changeHeaderImg() {
header.style.backgroundImage = "url(" + headerImages[i] + ")";
if(i < headerImages.length - 1){
i++;
} else {
i = 0;
}
setTimeout(changeHeaderImg(), time);
}
changeHeaderImg();
});
You are calling changeHeaderImg
and passing it's result to setTimeout
instead of passing changeHeaderImg
itself. 您正在调用
changeHeaderImg
并将其结果传递给setTimeout
而不是传递changeHeaderImg
本身。
So you are getting endless recursion which results in so-called "stack overflow" classic error. 因此,您将获得无穷的递归,从而导致所谓的“堆栈溢出”经典错误。
Try setTimeout(changeHeaderImg, time);
尝试
setTimeout(changeHeaderImg, time);
A function that calls itself is called a recursive function. 调用自身的函数称为递归函数。 Once a condition is met, the function stops calling itself.
一旦满足条件,该函数将停止调用自身。 This is called a base case.
这称为基本情况。
In some ways, recursion is analogous to a loop. 在某些方面,递归类似于循环。 Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case).
两者都多次执行相同的代码,并且都需要一个条件(避免无限循环,或者在这种情况下避免无限递归)。 When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.
当函数调用过多或函数缺少基本情况时,JavaScript将引发此错误。
function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
Setting this condition to an extremely high value, won't work: 将此条件设置为极高的值将不起作用:
function loop(x) {
if (x >= 1000000000000)
return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion
This recursive function is missing a base case. 此递归函数缺少基本情况。 As there is no exit condition, the function will call itself infinitely.
由于没有退出条件,因此该函数将无限调用自身。
function loop(x) {
// The base case is missinng
loop(x + 1); // Recursive call
}
loop(0);
// InternalError: too much recursion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.