假设用户正在单击按钮,时间为 ,假设为 0
与请求服务器端要做的第一件事是再次获取时间,假设这次也是 0,存储在名为 currenttime
的 var 中(使用 new Date() .getTime()
)
然后服务器开始工作,这需要一些时间,直到它调用一个函数来存储时间,并给用户一些等待时间。
问题是,假设我将当前时间变量发送到函数并保存它,并添加假设 90 分钟(1 1/2 小时)。
然后客户端,我检索用户需要等待的时间。 但在本例中,结果是 90 分钟(还有一些额外的秒,大约在 15-30 秒之间)。
如何确保在将请求发送到服务器后,用户不需要等待超过 90 分钟?
函数调用:
// after processing things this occurs
userData.updateTimers(userid, whattotime, 5400,currenttime);
5400 是 5400 秒,相当于 90 分钟。
当前时间是 new Date().getTime()
在查询中检索到的第一件事的变量。
实际功能:
function updateTimers(userid,type,sec,time) {
return new Promise( function (resolve, reject) {
var newtime = time + (sec * 1000);
var updateObj = {};
updateObj[type] = newtime;
usertimers.update({userid: userid},{$set: updateObj}).then(function (result) {
console.log("updated timers");
console.log(result);
return resolve(result);
})
});
}
再说一遍,我怎样才能将其设置为 90 分钟,而不包括处理时间? 我需要使计时器更新准确。
我正在使用 AngularJS 前端的平均堆栈。花时间在那里并将其带到服务器端以供将来使用是否是一种解决方法,或者我可以做更好的事情吗?
因为无论我在服务器端做什么并增加一些等待时间,它总是会多几秒钟:/
最佳答案
使用一个看门狗
来计时并测试日期偏移。
然后您可以将“完成”的日期 (new Date().getTime() + (1000 * 60 * 90)
) 发送给用户。
//Accurate timer using a watchdog
var Watchdog = (function () {
function Watchdog(waitMilliseconds, callback) {
if (callback === void 0) { callback = function () { }; }
this.waitMilliseconds = waitMilliseconds;
this.callback = callback;
this.start = new Date().getTime();
var self = this;
this.interval = setInterval(function () { self.test(); }, 1);
}
Watchdog.prototype.test = function () {
if (new Date().getTime() - this.start > this.waitMilliseconds) {
console.log(new Date().getTime() - this.start);
clearInterval(this.interval);
this.callback();
}
};
return Watchdog;
}());
new Watchdog(1000, function () {
console.log("A second has passed");
});
new Watchdog(1000 * 60 * 90, function () {
console.log("90 minutes has passed");
});
关于Javascript/Node 和计时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598143/