JSFiddle - React, Tailwind, and code Playground
by _abl
HTML
<input id="search"> <span id="remainingTimeDisplay"></span>
JavaScript
function programCountDown(){
$("#search").keydown(function(){
counter.reset({
onFinish : function(){
alert("Time's up!");
}
});
});
}
var counter = {
interval : null,
time : null,
initialTime : 2000,
stepTime : 10,
display : null,
init : function(){
this.display = $("#remainingTimeDisplay");
},
reset : function(pars){
this.onFinish = pars.onFinish;
if(this.interval){
clearInterval(this.interval);
}
this.time = this.initialTime;
this._displayTime();
this._set();
},
_set : function(){
this.interval = setInterval(function(){
counter.time -= counter.stepTime;
counter._displayTime();
if(counter.time <= 0){
clearInterval(counter.interval);
if($.isFunction(counter.onFinish)){
counter.onFinish();
}
}
}, counter.stepTime)
},
_displayTime : function(){
var digit1 = "" + Math.floor(counter.time / 1000);
var digit2 = "" + Math.floor((counter.time%1000) / 100);
var digit3 = "" + Math.floor((counter.time%100) / 10);
this.display.html(digit1 + "." + digit2 + digit3);
}
}
$(document).ready(function(){
counter.init();
programCountDown();
});