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

问题描述 投票:0回答:7

这里有一个简单的问题,我似乎找不到答案:一旦设置了

setTimeout
,有什么方法可以查看它是否仍然设置?

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

据我所知,当您

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

javascript settimeout
7个回答
78
投票

我所做的是:

var timer = null;

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

59
投票

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

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


29
投票

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

clearTimeout
即可。

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

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


5
投票

用计时器设置另一个变量

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.");
   }

}

3
投票

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

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

  1. t
    自..起的毫秒数在下一个目标的日期对象中
  2. timerSys
    为实际间隔
  3. seconds
    毫秒阈值已设置

接下来我有一个带有1个变量的

function timer
,该函数检查变量是否为truly,如果是,则检查计时器是否已经在运行,如果是这种情况,则填充global vars,如果不是trulyfalsely,清除间隔并将
global var timerSys
设置为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);

}

示例一

现在您可以向 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))

示例二

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


3
投票

我通常会取消计时器:

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!');
}

0
投票

我创建了一个计时器服务,如下所示,从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",
});

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

© www.soinside.com 2019 - 2024. All rights reserved.