I have the following situation:
我有以下情况:
I have a certain function that runs a loop and does stuff, and error conditions may make it exit that loop. I want to be able to check whether the loop is still running or not.
我有一个运行循环并执行操作的特定函数,错误条件可能使它退出该循环。我希望能够检查循环是否仍在运行。
For this, i'm doing, for each loop run:
为此,我正在做,为每个循环运行:
LastTimeIDidTheLoop = new Date();
And in another function, which runs through SetInterval every 30 seconds, I want to do basically this:
在另一个每隔30秒运行一次SetInterval的函数中,我想基本上这样做:
if (LastTimeIDidTheLoop is more than 30 seconds ago) {
alert("oops");
}
How do I do this?
我该怎么做呢?
Thanks!
4 个解决方案
#1
5
what about:
newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
alert("oops");
}
#2
7
JS date objects store milliseconds internally, subtracting them from each other works as expected:
JS日期对象在内部存储毫秒,相互减去它们按预期工作:
var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000;
if (diffSeconds > 30)
{
// ...
}
#3
0
You can do like this:
你可以这样做:
var dateDiff = function(fromdate, todate) {
var diff = todate - fromdate;
return Math.floor(diff/1000);
}
then:
if (dateDiff(fromdate, todate) > 30){
alert("oops");
}
#4
-1
Create a date object and use setSeconds().
创建日期对象并使用setSeconds()。
controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);
if (LastTimeIDidTheLoop > controlDate) {
...
#1
5
what about:
newDate = new Date()
newDate.setSeconds(newDate.getSeconds()-30);
if (newDate > LastTimeIDidTheLoop) {
alert("oops");
}
#2
7
JS date objects store milliseconds internally, subtracting them from each other works as expected:
JS日期对象在内部存储毫秒,相互减去它们按预期工作:
var diffSeconds = (new Date() - LastTimeIDidTheLoop) / 1000;
if (diffSeconds > 30)
{
// ...
}
#3
0
You can do like this:
你可以这样做:
var dateDiff = function(fromdate, todate) {
var diff = todate - fromdate;
return Math.floor(diff/1000);
}
then:
if (dateDiff(fromdate, todate) > 30){
alert("oops");
}
#4
-1
Create a date object and use setSeconds().
创建日期对象并使用setSeconds()。
controlDate = new Date();
controlDate.setSeconds(controlDate.getSeconds() + 30);
if (LastTimeIDidTheLoop > controlDate) {
...