2016-03-18 47 views
3

嘗試使用數組中的項目創建元素,該元素每隔一秒隨機選擇一個數組,直到數組爲空。當我不將元素追加到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最終會崩潰,循環的推移永遠這是沒有意義的對我來說。

+1

你是否考慮過在每次迭代中記錄數組的內容,然後它可能會顯示你爲什麼/哪裏出錯。例如:if(imgArray.length && iterationLimit)'(例如初始化'iterationLimit = 10'後)爲了防止無限循環在'if'中使用另一個變量,它只允許10次迭代;在這兩種情況下,'0'都是錯誤的,所以一旦數字中的任何一個達到'0','if'就會成爲'false'並停止)。 –

+2

我也很好奇,看看這個「加載」回調在更新DOM後被重新調用。 –

+0

我使用Meteor作爲我的框架 –

回答

1

好吧,你設置的時間間隔,它會保持一個自稱來檢查,如果每一秒後陣長是空的,即使那不是問題,我建議你做這樣的事情:

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); 

這樣,函數會自行調用並每秒返回一個結果,直到數組爲空。

現在要回到真正的問題: 您的'加載'功能可能被多次調用,設置了很多與相同數組的間隔。如果循環真的是無限的,那麼它可能會以某種方式調用它自己。 試着只留下一個控制檯登錄你的加載函數並運行你的腳本來查看日誌是否多次出現。

+0

這正是我想要完成的,非常感謝你! –

相關問題