JavaScript timer crosses 0 and gives -1
-
Comments from console time is :1 and then time is -1 without 0
'use strict';
app.timer = (function () {
var timeIsOver = true,
time = 0;
return {
//time measured in seconds
setTime: function (num) {
if (typeof num !== 'number') {
throw new TypeError();
}
time = num;
timeIsOver = false;
},
start: function () {
if (time === 0) return;
var that = this;
setTimeout(function () {
mediator.publish(app.eventNames.timeIsOverEvent, null);
that.reset();
}, time * 1000);
var intervalId = setInterval(function () {
if (timeIsOver || time === 0) {
clearInterval(intervalId);
}
time -= 1;
console.log('time is : ' + time)
mediator.publish(app.eventNames.timeTillTheEndEvent, {
timeTillTheEnd: time
});
}, 1000);
},
reset: function () {
timeIsOver = true;
time = 0;
}
};
})()
-
You have a function.
setTimeout
It works before it works.setInterval
It turns out that when the timer reaches the unit, and the idea was to take the next zero, it works.
reset()
and prematurely compelling. In the end, instead of whatsetInterval
in order to obtain a value 1, it receives 0 and reduces it by one extra unit -1.That's the idea.
SetTimeout
If you're not, you'll be fine without him.app.timer = (function () { var timeIsOver = true, time = 0; return { //time measured in seconds setTime: function (num) { if (typeof num !== 'number') { throw new TypeError(); } time = num; timeIsOver = false; }, start: function () { if (time === 0) return; var that = this; var intervalId = setInterval(function () { if (timeIsOver || time === 0) { mediator.publish(app.eventNames.timeIsOverEvent, null); clearInterval(intervalId); that.reset(); return; } time -= 1; console.log('time is : ' + time) mediator.publish(app.eventNames.timeTillTheEndEvent, { timeTillTheEnd: time }); }, 1000); }, reset: function () { timeIsOver = true; time = 0; } }; })()