【问题标题】:setTimeout with Date object带日期对象的 setTimeout
【发布时间】:2019-02-06 18:02:02
【问题描述】:

我正在根据用户输入创建超时,输入格式为:1min2h,并通过以下代码确定是一分钟还是一小时;

if (duration.includes("h", 1)) {
  /* If the collectedDuration includes "h" in it,
  parse the string into an integer and multiply it with an hour in miliseconds */
  const intDuration = parseInt(duration, 10);
  const parsedDuration = intDuration * 3600000;
  // Create the timer with setTimeout where parsedDuration is the delay
  createTimer(item, parsedDuration);
} else if (duration.includes("m", 1)) {
  const intDuration = parseInt(duration, 10);
  const parsedDuration = intDuration * 60000;
  createTimer(item, parsedDuration);
}

我想做的事:弄清楚在 setTimeout 在任何给定时间完成之前还剩下多少时间。例如:定时器创建1小时15分钟后,我使用命令显示剩余时间为45分钟。

我尝试了找到here的转换方法,但那是静态的;它仅将基本毫秒转换为小时。我需要一些动态的东西。

我也尝试过使用 Date 对象但失败了。我该怎么办?

【问题讨论】:

  • 你需要一个标签来显示剩余多少吗?
  • 您能否提供一个 sn-p minimal reproducible example 以便我们可以重现并了解您正在尝试做什么?
  • ^^ 帮助我们帮助你
  • 道歉。这是针对 Discord 机器人的,代码相当冗长。这是一段代码中的 sn-p,它会在一段时间内创建赠品。我想要做的是,在使用setTimeout 创建计时器后,使用一个命令显示赠品结束的时间。这个命令的完整代码可以在on GitHub找到。

标签: javascript datetime settimeout


【解决方案1】:

你不能用香草setTimeout 做到这一点。你必须把它包装起来:

class Timeout {
  // this is a pretty thin wrapper over setTimeout
  constructor (f, n, ...args) {
    this._start = Date.now() + n; // when it will start
    this._handle = setTimeout(f, n, ...args);
  }

  // easy cancel
  cancel () {
    clearTimeout(this._handle);
  }

  // projected start time - current time
  get timeLeft () {
    return this._start - Date.now();
  }
}

我希望他们首先为超时/间隔提供 OO 接口。用法:

const timeout = new Timeout(console.log, 2000, 'foo', 'bar');
setTimeout(() => console.log(timeout.timeLeft), 1000);

应该打印类似的东西

1000
foo bar

在几秒钟内。

【讨论】:

    【解决方案2】:

    这个答案不完整,更多的是建议。

    您说您未能尝试使用 Date 对象执行您需要的操作,请考虑使用 momentjs 库的任何方法。 Moment 使得修改 Date 比转换为 epoch 然后添加/减去 ms 容易得多。

    https://momentjs.com/

    您可以执行以下操作:

     var x = moment(); // sets x to now
     x.subtract(10, 'minute'); // subtracts 10 minutes
     console.log(x.format('MMMM Do YYYY, h:mm:ss a')); // see what you have now
    

    【讨论】:

      猜你喜欢
      • 2017-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      相关资源
      最近更新 更多