Random Number Generator BV2 p.31
by djwelsh
HTML
<div id="cont">
<div id="nums"></div>
</div>
CSS
#cont {
width: 720px;
height: 400px;
outline: 1px dashed #ccc;
font: 18em arial;
text-align: center;
margin: 40px auto;
background-color: white;
line-height: 400px;
cursor: none;
}
JavaScript
var nums = [
'1-1',
'1-2',
'1-3',
'1-4',
'1-5',
'1-6',
'1-7',
'1-8',
'1-9',
'1-10',
'1-11',
'1-12',
'2-1',
'2-2',
'2-3',
'2-4',
'2-5',
'2-6',
'2-7',
'3-1',
'3-2',
'3-3',
'3-4',
'3-5',
'3-6'
];
//Values we use for timeouts
var toVals = [10, 15, 20, 25, 30, 40, 50, 60, 80, 100, 120, 150, 180, 220, 260];
var cont = document.getElementById('cont');
cont.onclick = function (event) {
if (!event) event = window.event;
//Kill any current timeouts and start afresh if it is already in motion.
if (timer) {
clearTimeout(timer);
currentToVal = -1;
}
//Start the motion
nums = shuffleArray(nums);
flip();
}
var timer = null;
var currentToVal = -1;
var currentNum = 0;
function flip() {
currentToVal++;
//If there are no more toVals we have reached the last interval.
if (!toVals[currentToVal]) {
var nums2 = [];
for (var n = 0; n < nums.length; n++) {
if (nums[n] != currentNum) nums2.push(nums[n]);
}
nums = nums2;
currentToVal = -1;
timer = null;
}
//Otherwise call the timeout again with the next timeout value from toVals.
else {
timer = setTimeout(function () {
flip();
}, toVals[currentToVal]);
currentNum = nums[currentToVal % nums.length];
document.getElementById('nums').innerHTML = (currentNum) ? currentNum : '☺';
}
}
/**
* Randomize array element order in-place.
* Using Fisher-Yates shuffle algorithm.
* http://stackoverflow.com/a/12646864
*/
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}