create new element from array until array is empty every second

Viewed 1464

Trying to create an element using items from an array that are randomly selected every other second until array is empty. I am stumped why my function works when i don't append the element to the dom but as soon as i add to the dom the array just gets larger and ends up crashing the dom.

My plan is to eventually create a new object that has the image, css with random xy position and then append a new element to the dom using the object values.

Basically i am trying to add random images to the dom every second and have them animate in and out until the array is empty.

Any help would be greatly appreciated, thank you.

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

    },

This is the console when i don't append new image:

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

If i add the new image to the dom it will eventually crash and the loop goes on forever which makes no sense to me.

1 Answers
Related