在我的页面上,我有一段基于嵌套函数的简单代码,这有助于我以正确的顺序依次显示一个元素:
var fade = 700;
$('#s2icon-center').fadeIn(fade, function() {
$('#s2icon-1').fadeIn(fade, function() {
$('#s2icon-3, #s2icon-9').fadeIn(fade, function() {
$('#s2icon-6, #s2icon-11, #s2icon-17').fadeIn(fade, function() {
$('#s2icon-5, #s2icon-14, #s2icon-19').fadeIn(fade, function() {
$('#s2icon-8, #s2icon-13, #s2icon-22').fadeIn(fade, function() {
$('#s2icon-2, #s2icon-16, #s2icon-21').fadeIn(fade, function() {
$('#s2icon-4, #s2icon-10, #s2icon-24').fadeIn(fade, function() {
$('#s2icon-7, #s2icon-12, #s2icon-18').fadeIn(fade, function() {
$('#s2icon-15, #s2icon-20').fadeIn(fade, function() {
$('#s2icon-23').fadeIn(fade);
});
});
});
});
});
});
});
});
});
});
但在我看来,由于在一个地方使用了太多函数,页面变得迟缓并且我在控制台中收到错误消息:'Uncaught RangeError: Maximum call stack size exceeded'
现在我要问你们的问题是,如何(以最简单的方式)获得相同的效果但效率更高?
提前致谢!
------------ 编辑
它应该是这样的: Codepen Full view
代码就在这里: Codepen DEMO
最佳答案
您似乎有问题的是 animation回调:
Complete Function
If supplied, the complete callback function is fired once the animation is complete. This can be useful for stringing different animations together in sequence. The callback is not sent any arguments, but this is set to the DOM element being animated. If multiple elements are animated, the callback is executed once per matched element, not once for the animation as a whole.
这不是你想要的。相反,使用 promise
,这也应该防止堆栈溢出。
var fade = 700;
$('#s2icon-center').fadeIn(fade).promise().then(function() {
return $('#s2icon-1').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-3, #s2icon-9').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-6, #s2icon-11, #s2icon-17').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-5, #s2icon-14, #s2icon-19').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-8, #s2icon-13, #s2icon-22').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-2, #s2icon-16, #s2icon-21').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-4, #s2icon-10, #s2icon-24').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-7, #s2icon-12, #s2icon-18').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-15, #s2icon-20').fadeIn(fade).promise();
}).then(function() {
return $('#s2icon-23').fadeIn(fade).promise();
}).then(function() {
console.log("all finished");
});
关于javascript - 超过最大调用堆栈大小 - 知道为什么(函数太多)但如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22605804/