我想知道如何制作一个简单的倒数计时器,它可以在服务器上倒计时,但显示客户端还剩下多长时间。
答案 0 :(得分:1)
服务器:
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)
客户端:
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
}
})
然后只需在名为countdown的模板中调用客户端上的助手!