【发布时间】:2014-03-26 18:28:53
【问题描述】:
我正在创建一个包含一些简单计时器的 Meteor 应用程序。按下计时器上的开始或停止按钮都会调用一个方法来设置或清除间隔计时器等。当我setInterval时,我将生成的对象存储在当前的计时器文档中,以便以后我想清除间隔计时器时很容易找到。这就是我遇到问题的地方。
在服务器端运行Meteor.setInterval() 时,它返回一个对象。根据 node.js 文档,这是正常的。如果我在创建后记录结果对象,它会返回:
{ _idleTimeout: 5000,
_idlePrev:
{ _idleNext: [Circular],
_idlePrev:
{ _idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Circular],
_idleStart: 1393271941639,
_onTimeout: [Function],
_repeat: false },
msecs: 5000,
ontimeout: [Function: listOnTimeout] },
_idleNext:
{ _idleTimeout: 5000,
_idlePrev: [Circular],
_idleNext:
{ _idleTimeout: 5000,
_idlePrev: [Circular],
_idleNext: [Object],
_idleStart: 1393271941639,
_onTimeout: [Function],
_repeat: false },
_idleStart: 1393271941639,
_onTimeout: [Function],
_repeat: false },
_idleStart: 1393271943127,
_onTimeout: [Function: wrapper],
_repeat: true }
如果我在从文档中检索对象后记录它,我会得到:
{ _idleTimeout: 5000,
_idlePrev: null,
_idleNext: null,
_idleStart: 1393271968144,
_repeat: true }
因此,将clearInterval 与此一起使用是行不通的。这是我的服务器端代码:
Meteor.methods({
play: function(entry){ //entry is the document
var currentPlayTimer = entry; //Global variable for the interval timer
Entries.update({_id: currentPlayTimer._id},{$set:{playing:true}}); //This is mostly to set the status of the play button for the client
var IntervalId = Meteor.setInterval(function(){Entries.update({_id: currentPlayTimer._id},{$inc:{time:1},$set:{intervalId: IntervalId}});},5000); //Increment by 1 every 5 seconds, put the object from the interval timer into the current document
console.log(IntervalId);
},
stop: function(entry){ //entry is the document
var currentPlayTimer = entry;
IntervalId = currentPlayTimer.intervalId;
console.log(IntervalId);
Meteor.clearInterval(IntervalId);
Entries.update({_id: currentPlayTimer._id},{$set:{playing:false, intervalId: null}});
}
});
另外,你会注意到在 play 方法中,我在 setInterval 函数中设置了 intervalId。我绝望地尝试了这个,它奏效了。出于某种原因,如果我在使用 Entries.update({_id: currentPlayTimer._id},{$set:{intervalId: IntervalId}}) 创建间隔计时器后立即尝试更新文档,则会失败。
所有这些都作为客户端代码工作得很好,但我需要在服务器端完成。无论您是否在 5 台设备上打开页面,我都希望计时器以正确的速度运行。
感谢您的帮助!这个项目是我第一次在 Node 上使用 Meteor 或任何东西,到目前为止我真的很喜欢它。
【问题讨论】:
标签: javascript node.js mongodb meteor setinterval