Code double posted from http://board.phpbuilder.com/showthread.php?10390505-Countdown-Timer&p=11032061&viewfull=1#post11032061 to avoid thread hijacking
var Timer = (function(w, el, elid) {
var id = null;
var cycles = 5;
var p = {
setCycles : function(i) {
i = parseInt(i);
if (isNaN(i))
throw 'not a number';
if (i <= 0)
throw 'Out of range';
cycles = i;
// Question #1: Why is it not possible to use el directly here
el.html(cycles);
// while creating new jquery objects work fine
jQuery('#'+elid).html(cycles);
},
start : function(ms) {
ms = parseInt(ms);
if (isNaN(ms))
throw 'not a number';
if (ms <= 0)
throw 'Out of range';
if (id == null && cycles > 0) {
id = w.setInterval(this.cycle, ms);
}
},
stop : function() {
if (id != null) {
w.clearInterval(id);
id = null;
}
},
cycle : function() {
--cycles;
// Question #1 all over again
el.html(cycles);
jQuery('#'+elid).html(cycles);
if (cycles <= 0) {
// Question #2: Why doens't this.stop() work?
// Or perhaps I should ask why this is window here, while this above is Timer.
// And is there a workaround or better way to write the code?
Timer.stop();
}
}
}
jQuery(document).ready(function($) {
$('#setCycles').on('click', function(evt) {
p.setCycles($(evt.target).siblings('input').prop('value'));
});
$('#start').on('click', function(evt) {
p.start(1000);
});
$('#stop').on('click', function(evt) {
p.stop();
});
});
return p;
})(window, jQuery('#display'), 'display');
See comments inside the code to find the code corresponding to my questions.
Question #1: jQuery('#display') is passed as a function argument and bound to the formal parameter el, but using el.html() doesn't work. However, passing 'display' to the formal parameter elid and using jQuery('#'+elid) works fine. How come?
Question #2: Inside the function Timer.start, the function Timer.cycle is referenced using this.cycle. However, inside Timer.cycle, using this.stop doesn't work. I have to use Timer.stop. this no longer references the Timer object, but actually references window. How come? I understand that cycle is called due to our call to window.setInterval, and thus I'm guessing that the calling context is window. But still, the cycle function resides inside Timer and this surely ought to be Timer inside Timer rather than other things depending on what the calling code is. Except that it isn't. I'd really appreciate a detailed explanation.