我创建了一个每隔500毫秒写入MongoDb的计时器。我这样做是为了让订阅的每个客户看到相同的Timer。但是,当我运行它时,我收到错误:
流星代码必须始终在光纤内运行。尝试使用Meteor.bindEnvironment包装传递给非Meteor库的回调。
我一直在阅读有关Meteor.bindEnviroment的内容,但不了解如何将其应用于我的代码。有什么想法吗?
Meteor.methods({
updateTime: function() {
var id = PlayersList.find().fetch()[0]._id;
var running = false;
var seconds = 20000; // (1 sec = 1000)
var then; // Timer start time
// ------------------------------------
// Evaluate and route
// ------------------------------------
function router(id) {
if (!running) {
run(id);
}
};
// ------------------------------------
// Run the timer
// ------------------------------------
function run(id) {
running = true;
then = Date.now() + seconds;
var interval = setInterval(function(){
var time = parseTime(then-Date.now());
if (time[0] > 0) {
var time = time[0] + '.' + time[1];
PlayersList.update({ _id: id }, { $set:{time : time }});
// console.log(time);
} else {
console.log('0.00');
running = false;
clearInterval(interval);
router();
}
}, 500);
};
// ------------------------------------
// Parse time in MS for output
// ------------------------------------
function parseTime(elapsed) {
// Array of time multiples [sec, decimal]
var d = [1000,10];
var time = [];
var i = 0;
while (i < d.length) {
var t = Math.floor(elapsed/d[i]);
// Remove parsed time for next iteration
elapsed -= t*d[i];
t = (i > 0 && t < 10) ? '0' + t : t;
time.push(t);
i++;
}
return time;
};
router(id);
}
});