info343/minilabs/6/solution/minilab6-ex5.js

// minilab6-ex5.js
// Sample JavaScript solution for Mini-Lab 6: Timers
// INFO 343, Autumn 2012
// Morgan Doocy

var timer = null;

// Attach click handler to #begin button when the document is ready.
$(document).ready(function() {
   $('#begin').click(startTimer);
});

// Begin the countdown timer.
function startTimer() {
/*[<ins>]*/   if (timer === null) { // ensure we don't start multiple timers/*[</ins>]*/
      timer = setInterval(countDownByOne, 1000);
/*[<ins>]*/   }/*[</ins>]*/
}

// Decrement the number in #seconds by one. If the number is zero, stop the
// countdown.
function countDownByOne() {
   var seconds = $('#seconds').val();
   if (seconds > 0) {
      $('#seconds').val(seconds - 1);
      injectRect();
   } else {
      clearInterval(timer);
      timer = null;
   }
}

/*[<ins>]*/// Create and inject a new div.rect into the page, at a random location and with
// a random color. The rect will remove itself from the page when clicked.
function injectRect() {
   // generate random x/y coordinates
   var left = Math.floor(Math.random() * (window.innerWidth - 50));
   var top = Math.floor(Math.random() * (window.innerHeight - 50));
   
   // generate random red/green/blue values (0-255)
   var r = Math.floor(Math.random() * 255);
   var g = Math.floor(Math.random() * 255);
   var b = Math.floor(Math.random() * 255);
   
   // create a new rect and give it the appropriate styles
   var $rect = $('<div>').addClass('rect');
   $rect.css({
      'left': left,
      'top': top,
      'background-color': 'rgb(' + r + ', ' + g + ', ' + b + ')'
   });
   
   // make the rect remove itself when clicked
   $rect.click(function() {
      $(this).remove();
   });
   
   // inject the rect into the page
   $rect.appendTo(document.body);
}/*[</ins>]*/