I have encountered a problem with my counter. I don't know why but the clearInterval(timeinterval) doesn't fire. If i put a console.log statement for t it is going to -1, -2, etc.. why isn't the counter stopping?
Template.decision.onRendered(function(){
timeinterval = setInterval(function () {
var endtime = '2016/02/10'
Meteor.call("getCurrentTime", function (error, result) {
Session.set("time", result);
var t = getTimeRemaining(endtime);
Session.set("t", t);
});
}, 1000);
});
function getTimeRemaining(endtime){
var t = Date.parse(endtime) - Session.get('time');
var seconds = ("0" + Math.floor( (t/1000) % 60 )).slice(-2);
var minutes = ("0" + Math.floor( (t/1000/60) % 60 )).slice(-2);
var hours = ("0" + Math.floor( (t/(1000*60*60)) % 24 )).slice(-2);
var days = Math.floor( t/(1000*60*60*24) );
console.log(t);
if(t <= 0) {
clearInterval(timeinterval);
}
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
And on my server:
Meteor.methods({
'getCurrentTime': function (){
return Date.parse(new Date());
}
});
if(t <= 0 && timeinterval) {
clearInterval(timeinterval);
}
To not to have duplicate timers, either you can cancel the previous interval in the line before you set the new timer, or you can do:
if (!timeinterval) {
timeinterval = setInterval(function () {
timeinterval = null;
}, delay);
}
But this can be tricky when you have concurrency.