I was wondering how to make a simple countdown timer that would countdown on the server, but show how long was left on the client.
Server:
timeToClear.remove({}); //Removes the previous time calls
Meteor.setInterval(function(){ //The Actual Countdown
Messages.insert({
name: "[Server]",
message: "<div class='animated infinite flash'>Attention! Chat will be cleared in 15 seconds!<br>Note: Chat is cleared every 12 hours</div>",
time: moment().format('MMMM Do , h:mm a'),
uid: Messages.find().fetch().length + 1,
email: "Server Function"
});
Meteor.setTimeout(function () {
Messages.remove({});
}, 15000);
}, 28800000);
time = 28000000; //Sets the ammount of time to countdown
uid = 0;
Meteor.setInterval(function(){ //The part that allows the client to see it
console.log(uid);
timeToClear.insert({
time: time,
uid: uid
})
time = time - 1000;
uid = uid + 1;
if(time === 0){
time = 28000000; //Resets time after countdown is complete
uid = 0;
timeToClear.remove({}); //Removes all previous time calls
}
}, 1000)
Client:
Template.countdown.helpers({
timer: function (){
x = timeToClear.find({}, { sort: { uid: -1}}).fetch()[0].time; //Gets the highest (newest) uid, and gets the time from it
var tempTime = moment.duration(x); //Converts it into a nicer format using moment
var hours = tempTime.hours();
var minutes = tempTime.minutes();
var seconds = tempTime.seconds();
return "Time till messages are cleared: " +hours + ":" + minutes + ":" + seconds; //Returns it to helper
}
})
Then simply call the helper on the client in a template called countdown!