尝试使用每隔一秒随机选择的数组中的项创建元素,直到数组为空。当我不将元素附加到dom时,我很难理解为什么我的函数会工作,但是我一将元素添加到dom中,数组就会变大,最终导致dom崩溃。
我的计划是最终创建一个具有图像的新对象,即具有随机xy位置的css,然后使用对象值向dom添加一个新元素。
基本上,我试图每秒钟向dom添加随机图像,并让它们在数组为空之前进行动画处理。
任何帮助都将不胜感激,谢谢。
"load": function(){
var imgArray = ['brain', 'mitochondria', 'microscope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
window.setInterval(function(){
var imgItem;
if( imgArray.length >= 1 ) {
var index = Math.floor( Math.random()*imgArray.length );
console.log( imgArray[index] ); // Log the item
imgItem = ( imgArray[index] ); // Log the item
imgArray.splice( index, 1 ); // Remove the item from the array
// $('form').append('<img class="img-animation" src="img/science/'+ imgItem +'.svg" alt="'+ imgItem +'">');
}
}, 1000);
},这是当我不添加新图像时的控制台:
home.js:11 beaker
home.js:11 dropper
home.js:11 microscope
home.js:11 beaker-2
home.js:11 atom
home.js:11 brain
home.js:11 scientist
home.js:11 cell
home.js:11 mitochondria如果我将新的图像添加到dom中,它最终会崩溃,循环将永远持续下去,这对我来说毫无意义。
发布于 2016-03-18 15:36:52
好的,您正在设置一个间隔,它将继续调用自己,以检查数组空后很长时间内是否每秒钟检查一次,即使这不是我建议您执行以下操作的问题:
var imgArray = ['brain', 'mitochondria', 'microscope', 'beaker', 'beaker-2', 'scientist', 'cell', 'atom', 'dropper'];
var getAllRandomly = function(arr) {
if (arr.length) {
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]); // Log the item
imgItem = (arr[index]); // Log the item
imgArray.splice(index, 1); // Remove the item from the array
setTimeout(function() {
getAllRandomly(arr);
}, 1000);
}
else {
console.log('Array is empty');
}
};
getAllRandomly(imgArray);这样,函数将调用自己并每秒钟返回一个结果,直到数组为空。
现在来看真正的问题:您的'load‘函数可能被多次调用,使用相同的数组设置很多时间间隔。如果循环真的是无限的,那么它可能在某种程度上调用自己。试着在load函数上只留下一个控制台日志,然后运行您的脚本,查看日志是否多次出现。
https://stackoverflow.com/questions/36087437
复制相似问题