I've tried to simplify a problem I'm having with the code below. Some of the code relies on jQuery, fyi.
Basically, I expect that when 'New Thing' is clicked, a single alert message will appear. However, if one starts the timer, clicking 'New Thing' results in an unexpected behavior where the number of alert messages that appear is equal to the time elapsed.
This problem is destroying me.
To be thorough, I've included a complete example. I realize it's a bit lengthy.
$(document).ready(function() {
mainLoop();
});
var counter = 0;
var timerIsOn = 0;
var t;
function mainLoop() {
handleInput();
timer();
}
function timerHandle() {
if (!timerIsOn){
timerIsOn = 1;
timer();
}
}
function timer(){
if (timerIsOn) {
t = setTimeout(mainLoop, 1000);
counter++;
$("span").text(counter); // To display the elapsed time
}
}
// Just simple buttons
function handleInput(){
$("#timer").click(timerHandle);
$("#new").click(createThing);
}
function Thing() {
this.talk();
}
Thing.prototype.talk = function() {
alert("Hello!");
}
function createThing() {
new Thing;
}
I really appreciate the help!