Little Chunks of Blocks, Stop Start

Simple control of interval animations

by Steven Senkus

HTML

<div id="target"></div>
<button id="start">Start</button>
<button id="stop">Stop</button>

CSS

#target {
    width: 500px;
    height: 300px;
    border: 2px solid #000;
}
#start {
    position: absolute;
    top: 30px;
    right: 120px;
}
#stop {
    position: fixed;
    top: 30px;
    right: 60px;
}
.box {
    height:5px;
    width:5px;
    float:left;
}
.box:hover {
    background-color: #fff;
}
.red {
    background-color: #f00;
}
.orange {
    background-color: #f70;
}
.yellow {
    background-color: #ff0;
}
.green {
    background-color: #070;
}
.blue {
    background-color: #007;
}
.indigo {
    background-color: #00f;
}
.violet {
    background-color: #707;
}

JavaScript

$(document).ready(function () {

    
        
    // A good practice to get used to in JS is to put all of your 
    // variables and functions at the top of your program
    // look up "javascript variable hoisting" for more info


    // instead of using colors, use classes
    var color_array = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"];

    // jQuery can be computationally expensive, 
    // so you cache (store) the jQuery object you created 
    // in a variable
    var $target = $('#target');
    var timer;
    var animSpeed = 100;    
    
    // if you repeat code, it's time to refactor
    function getRandomColor(arr) {
        return arr[Math.floor(Math.random() * arr.length)];
    }

    function addBoxes() {
        // declaring the i variable here is faster for lookup
        var i;
        for (i = 0; i < 10; i++) {
            // always start at zero with loops,
            // it's just good practice
            $target.append('<div class="box ' + getRandomColor(color_array) + '"></div>');
        }

    }

    var started = false;
    
    // EVENT HANDLERS
    $('#start').on('click', function () {
        if (!started) {
        timer = setInterval(addBoxes, animSpeed);
            
                started = true;
        }
    });

    // good to stop buggy programs from crashing/freezing
    $('#stop').on('click', function () {
        clearInterval(timer)
        started = false
    });

});