我可以查看计时器是否仍在运行吗?

发布于 2024-09-09 02:37:58 字数 366 浏览 7 评论 0原文

这里有一个简单的问题,我似乎找不到答案:设置 setTimeout 后,有什么方法可以查看它是否仍然设置?

if (!Timer)
{
    Timer = setTimeout(DoThis,60000);
}

据我所知,当您clearTimeout时,变量将保持其最后的值。我刚刚查看的 console.log 显示 Timer 为“12”,无论超时是否已设置或清除。我是否也必须将变量清空,或者使用其他变量作为布尔值,说“是的,我已经设置了这个计时器”?当然有一种方法可以检查超时是否仍在运行......对吧?我不需要知道还剩多长时间,只要知道它是否仍在运行即可。

Simple question here that I can't seem to find an answer for: Once a setTimeout is set, is there any way to see if it's still, well, set?

if (!Timer)
{
    Timer = setTimeout(DoThis,60000);
}

From what I can tell, when you clearTimeout, the variable remains at its last value. A console.log I just looked at shows Timer as being '12', no matter if the timeout has been set or cleared. Do I have to null out the variable as well, or use some other variable as a boolean saying, yes, I have set this timer? Surely there's a way to just check to see if the timeout is still running... right? I don't need to know how long is left, just if it's still running.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

别低头,皇冠会掉 2024-09-16 02:37:58

我所做的是:

var timer = null;

if (timer != null) {
  window.clearTimeout(timer); 
  timer = null;
}
else {
  timer = window.setTimeout(yourFunction, 0);
}

What I do is:

var timer = null;

if (timer != null) {
  window.clearTimeout(timer); 
  timer = null;
}
else {
  timer = window.setTimeout(yourFunction, 0);
}
叶落知秋 2024-09-16 02:37:58

除了启动或停止计时器之外,无法与计时器进行交互。我通常将超时处理程序中的计时器变量设置为空,而不是使用标志来指示计时器未运行。 W3Schools 上有关于计时器如何工作的很好的描述。在他们的示例中,他们使用标志变量。

您看到的值是当前的句柄计时器,当您清除(停止)它时使用它。

There isn't anyway to interact with the timer except to start it or stop it. I typically null the timer variable in the timeout handler rather than use a flag to indicate that the timer isn't running. There's a nice description on W3Schools about how the timer works. In their example they use a flag variable.

The value you are seeing is a handle to the current timer, which is used when you clear (stop) it.

梦魇绽荼蘼 2024-09-16 02:37:58

无需检查现有计时器,只需在启动计时器之前执行clearTimeout即可。

var timer;
//..
var startTimer = function() {
  clearTimeout(timer);
  timer = setTimeout(DoThis, 6000);
}

这将在启动新实例之前清除所有计时器。

There is no need to check for an existing timer, just execute clearTimeout before starting the timer.

var timer;
//..
var startTimer = function() {
  clearTimeout(timer);
  timer = setTimeout(DoThis, 6000);
}

This will clear any timer before starting a new instance.

妳是的陽光 2024-09-16 02:37:58

使用计时器设置另一个变量 Timer_Started = true。并且在调用计时器函数时将变量更改为 false:

// set 'Timer_Started' when you setTimeout
var Timer_Started = true;
var Timer = setTimeout(DoThis,60000);

function DoThis(){

   // function DoThis actions 
   //note that timer is done.
   Timer_Started = false;

}

function Check_If_My_Timer_Is_Done(){

   if(Timer_Started){
      alert("The timer must still be running.");
   }else{
      alert("The timer is DONE.");
   }

}

Set another variable Timer_Started = true with your timer. And also change the variable to false when the timer function is called:

// set 'Timer_Started' when you setTimeout
var Timer_Started = true;
var Timer = setTimeout(DoThis,60000);

function DoThis(){

   // function DoThis actions 
   //note that timer is done.
   Timer_Started = false;

}

function Check_If_My_Timer_Is_Done(){

   if(Timer_Started){
      alert("The timer must still be running.");
   }else{
      alert("The timer is DONE.");
   }

}
土豪我们做朋友吧 2024-09-16 02:37:58

我知道这是一个死亡帖子,但我认为仍然有人在寻找它。

这就是我使用的:
3 个变量:

  1. t 表示毫秒,因为在下一个目标的日期对象中
  2. timerSys 表示实际间隔
  3. 毫秒阈值已

在下一个 i 中 设置有一个带有 1 个变量的函数计时器,该函数检查变量是否真正,如果是,则检查计时器是否已经在运行,如果是这种情况,则填充 global vars,如果不是truefalsely,则清除间隔并将global var timeSys设置为false;

var t, timerSys, seconds;

function timer(s) {
  if (s && typeof s === "number") {
    if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
      timerSys = setInterval(function() {
        sys();
      }, s);
      t = new Date().setMilliseconds(s);
      seconds = s;
    }
  } else {
    clearInterval(timerSys);
    timerSys = false;
  }
  return ((!timerSys) ? "0" : t)
}

function sys() {
  t = new Date().setMilliseconds(seconds);

}

示例 I

现在您可以向 sys 函数添加一行:

function sys() {
  t = new Date().setMilliseconds(seconds);
  console.log("Next execution: " + new Date(t));
//this is also the place where you put functions & code needed to happen when interval is triggerd

}

并执行:

  timer(5000);

控制台中每 5 秒:

  //output:: Next execution: Sun May 08 2016 11:01:05 GMT+0200 (Romance (zomertijd))

示例 II

function sys() {
  t = new Date().setMilliseconds(seconds);
  console.log("Next execution: " + seconds/1000 + " seconds");

}

$(function() {
  timer(5000);
});

控制台中每 5 秒:

      //output:: Next execution: 5 seconds

示例三

var t, timerSys, seconds;

function timer(s) {
  if (s && typeof s === "number") {
    if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
      timerSys = setInterval(function() {
        sys();
      }, s);
      t = new Date().setMilliseconds(s);
      seconds = s;
    }
  } else {
    clearInterval(timerSys);
    timerSys = false;
  }
  return ((!timerSys) ? "0" : t)
}

function sys() {
  t = new Date().setMilliseconds(seconds);
  console.log("Next execution: " + seconds / 1000 + " seconds");

}

$(function() {
  timer(5000);

  $("button").on("click", function() {
    $("span").text(t - new Date());
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Freebeer</button>
<span></span>

请注意,这样您可以低于 0

I know this is a necroposting but i think still people are looking for this.

This is what i use:
3 variables:

  1. t for milliseconds since.. in Date Object for next target
  2. timerSys for the actual interval
  3. seconds threshold for milliseconds has been set

next i have a function timer with 1 variable the function checks if variable is truly, if so he check if timer is already running and if this is the case than fills the global vars , if not truly, falsely, clears the interval and set global var timerSys to false;

var t, timerSys, seconds;

function timer(s) {
  if (s && typeof s === "number") {
    if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
      timerSys = setInterval(function() {
        sys();
      }, s);
      t = new Date().setMilliseconds(s);
      seconds = s;
    }
  } else {
    clearInterval(timerSys);
    timerSys = false;
  }
  return ((!timerSys) ? "0" : t)
}

function sys() {
  t = new Date().setMilliseconds(seconds);

}

Example I

Now you can add a line to sys function:

function sys() {
  t = new Date().setMilliseconds(seconds);
  console.log("Next execution: " + new Date(t));
//this is also the place where you put functions & code needed to happen when interval is triggerd

}

And execute :

  timer(5000);

Every 5 seconds in console:

  //output:: Next execution: Sun May 08 2016 11:01:05 GMT+0200 (Romance (zomertijd))

Example II

function sys() {
  t = new Date().setMilliseconds(seconds);
  console.log("Next execution: " + seconds/1000 + " seconds");

}

$(function() {
  timer(5000);
});

Every 5 seconds in console:

      //output:: Next execution: 5 seconds

Example III

var t, timerSys, seconds;

function timer(s) {
  if (s && typeof s === "number") {
    if (typeof timerSys === "boolean" || typeof timerSys === "undefined") {
      timerSys = setInterval(function() {
        sys();
      }, s);
      t = new Date().setMilliseconds(s);
      seconds = s;
    }
  } else {
    clearInterval(timerSys);
    timerSys = false;
  }
  return ((!timerSys) ? "0" : t)
}

function sys() {
  t = new Date().setMilliseconds(seconds);
  console.log("Next execution: " + seconds / 1000 + " seconds");

}

$(function() {
  timer(5000);

  $("button").on("click", function() {
    $("span").text(t - new Date());
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Freebeer</button>
<span></span>

Note this way you can go below 0

数理化全能战士 2024-09-16 02:37:58

我通常取消计时器:

var alarm = setTimeout(wakeUpOneHourLater, 3600000);
function wakeUpOneHourLater() {
    alarm = null;    //stop alarm after sleeping for exactly one hour
}
//...
if (!alarm) {
    console.log('Oops, waked up too early...Zzz...');
}
else {
    console.log('Slept for at least one hour!');
}

I usually nullify the timer:

var alarm = setTimeout(wakeUpOneHourLater, 3600000);
function wakeUpOneHourLater() {
    alarm = null;    //stop alarm after sleeping for exactly one hour
}
//...
if (!alarm) {
    console.log('Oops, waked up too early...Zzz...');
}
else {
    console.log('Slept for at least one hour!');
}
想你只要分分秒秒 2024-09-16 02:37:58

我创建了一个从timer.ts导出的计时器服务,如下所示 -

    import { setIntoStorage } from "./storage";

    type TimeoutInfo = {
      key: string;
      timeOutDate: string;
      purpose?: string;
    };

    const kActiveTimersKey = "app-active-timers";

    class Timers {
      private static instance: Timers;
      private static activeTimers: TimeoutInfo[] = [];

      constructor() {
        if (Timers.instance) {
          return Timers.instance;
        }

        Timers.instance = this;
      }

      async addTimeoutEntry(timeoutInfo: TimeoutInfo): Promise<void> {
        this.removeTimeoutEntry(timeoutInfo.key);
        Timers.activeTimers.push(timeoutInfo);
        await setIntoStorage(kActiveTimersKey, Timers.activeTimers);
      }

      async removeTimeoutEntry(key: string): Promise<void> {
        Timers.activeTimers = Timers.activeTimers.filter((v) => v.key !== key);
        await setIntoStorage(kActiveTimersKey, Timers.activeTimers);
      }
    }

    export const TimerService = new Timers();

我在创建或清除超时时使用它 -


    if (timer) {
      clearTimeout(timer);
      timer = null;
      TimerService.removeTimeoutEntry("AUTO_LOGOUT_TIMER");
    }


    timer = setTimeout(() => {
      dispatch(signUserOut());
    }, timeoutTime);

    const now = new Date();

    TimerService.addTimeoutEntry({
      key: "AUTO_LOGOUT_TIMER",
      timeOutDate: new Date(now.getTime() + timeoutTime).toLocaleString(),
      purpose: "Auto logout user when the JWT token expires",
    });

添加/删除计时器服务会产生一些开销,但它会显示在本地存储中以供快速检查。我很少使用这项服务,因为我的应用程序中没有设置太多超时。

在indexedDb中显示如下 -
输入图片此处描述

I created a timer service as below exported from timer.ts -

    import { setIntoStorage } from "./storage";

    type TimeoutInfo = {
      key: string;
      timeOutDate: string;
      purpose?: string;
    };

    const kActiveTimersKey = "app-active-timers";

    class Timers {
      private static instance: Timers;
      private static activeTimers: TimeoutInfo[] = [];

      constructor() {
        if (Timers.instance) {
          return Timers.instance;
        }

        Timers.instance = this;
      }

      async addTimeoutEntry(timeoutInfo: TimeoutInfo): Promise<void> {
        this.removeTimeoutEntry(timeoutInfo.key);
        Timers.activeTimers.push(timeoutInfo);
        await setIntoStorage(kActiveTimersKey, Timers.activeTimers);
      }

      async removeTimeoutEntry(key: string): Promise<void> {
        Timers.activeTimers = Timers.activeTimers.filter((v) => v.key !== key);
        await setIntoStorage(kActiveTimersKey, Timers.activeTimers);
      }
    }

    export const TimerService = new Timers();

I use this whilst creating or clearing a timeout -


    if (timer) {
      clearTimeout(timer);
      timer = null;
      TimerService.removeTimeoutEntry("AUTO_LOGOUT_TIMER");
    }


    timer = setTimeout(() => {
      dispatch(signUserOut());
    }, timeoutTime);

    const now = new Date();

    TimerService.addTimeoutEntry({
      key: "AUTO_LOGOUT_TIMER",
      timeOutDate: new Date(now.getTime() + timeoutTime).toLocaleString(),
      purpose: "Auto logout user when the JWT token expires",
    });

A bit of overhead to add/remove to timer service but it shows up in the local storage for a quick check. I have very few use for this service since I don't have much timeouts set in my app.

Showed like this in the indexedDb -
enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文