Something strange with your code is that there is no call to the "private" _start()
function, but nvm.
You should add a public reset()
function to :
- set the new
remaining
value, - clearInterval,
- then call the
_start()
function
You should then call this reset()
function when needed. Have a look in this code and explanations below :
(function($) {
$.widget('time.countdown', {
options : {
remaining : (2 * 24 * 60 * 60 * 1000),
updatefreq: 1000
},
_create : function () {
'use strict';
this._start();
},
_setOption: function(key, value) {
key == 'remaining' ?
this.reset(value) :
this._super(key, value);
},
_start: function () {
'use strict';
// your countdown code
},
reset: function(remaining) {
// You should perform some checks on the given value
this.options.remaining = remaining;
this._destroy();
this._start();
},
_destroy: function() {
'use strict';
if (this.interval !== undefined)
window.clearInterval(this.interval);
this.element.html('');
}
});
})(jQuery);
Note that the _create()
function is called only once, at creation time. So if you apply the plugin many times on the same element with no args like $('#timer').countdown();
then the _start()
will be called only once (on first call).
You can now reset the countdown with a new value in differents ways :
// new value to set = 3600
// Call to the "public" `reset()` function
$('#timer').countdown('reset', 3600);
// Call to the `_setOption()`
$('#timer').countdown({remaining: 3600});
// Call to the `_setOption()`
$('#timer').countdown('option', 'remaining', 3600);