$(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
});
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.