好的标题已经说明了。我正在研究一个计时器,但是当我让它运行大约10秒时,按空格(空格=键码13),然后它停止然后如果我再次按空格键开始,它会恢复,但然后+2 secondes。 (从例如18秒开始,从20秒开始恢复)来自它返回的clearInterval ID我认为......不确定。
如果你们能帮助我,那就太好了。
如果您有任何不同的做法,请让我知道!
我对我得到的所有反馈以及我的代码的改进/提示持开放态度! :)
的Javascript
var Timer = function() {
var self = this,
div = document.querySelector('.timer'),
hours, minutes, seconds, millsecs;
this.oldDate = new Date().getTime();
this.newDate;
this.isRunning = false;
this.time;
this.timerId = 0;
this.start = function() {
self.isRunning = true;
if (self.isRunning) {
self.timerId = setInterval(function() {
self.time = new Date().getTime() - self.oldDate;
self.time = self.time.toString();
millsecs= self.time.substr(-3);
seconds = (Math.floor(self.time / 1000) % 60) + '.';
minutes = (self.time >= 60000) ? (Math.floor(self.time / (1000*60)) % 60) + ':' : '';
hours = (self.time >= 86400) ? (Math.floor(self.time / (1000*60*60)) % 24) + ':' : '';
div.innerHTML = hours + minutes + seconds + millsecs;
}, 10);
}
}
this.stop = function() {
self.isRunning = false;
clearInterval(obj.timerId);
self.timerId = 0;
}
};
var obj = new Timer();
window.addEventListener('keyup', function(e) {
if(e.keyCode == 32 && obj.isRunning == false) {
obj.start();
}
else if (e.keyCode == 32 && obj.isRunning == true) {
obj.stop();
}
});