I am trying to create a front-end to a task management system, and I'm stuck on a setTimeout problem. I am trying to make it so that when a user clicks the checkbox, the tile fades to 33% opacity/toggle a "completed" class, waits 2 seconds, and then disappears; if the user clicks again on the checkbox before it disappears, the task should toggle the class and clear the timeout.
I am having a lot of trouble getting the clearTimeout command to work. I have declared my timer variable outside of the relevant blocks, tried adding the clearQueue() and stop() commands to my function, and triple-checked spelling.
My JS fiddle is here: http://jsfiddle.net/sLYA9/.
Here is my relevant JS:
$('#alltasks .taskitem form').click( function ( event ) {
event.preventDefault();
// Variables for different referenced elements
var tile = $( this ).parent('.taskitem');
var taskContents = '<div class=\'taskitem\' draggable=\'true\'>' + tile.html() + '</div>';
var timer;
// Unchecking a checked task
if (tile.hasClass('completed')) {
clearTimeout( timer );
tile.clearQueue().stop().fadeTo( 300, 1 );
} else { // Checking an unchecked task
tile.fadeTo( 300, 0.33 );
timer = setTimeout( function() {
alert("the task disappears");
}, 2000 );
}
tile.toggleClass('completed');
});
Again, I would like the user to be able to click the checkbox again before the 2000 ms timer is up and clear the timer.
Any ideas what I missed?
EDIT: I feel silly now. Moving my timer declaration outside of the click handler function made it work properly.