javascript - setTimeout 与日期对象

标签 javascript datetime settimeout

我正在根据用户输入创建超时,输入格式为: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 完成之前的任何给定时间计算出在 setTimeout 完成之前还剩下多少时间。例如:定时器创建为 1 小时 15 分钟后,我使用命令显示剩余时间为 45 分钟。

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

我也尝试过使用 Date 对象,但失败了。我该如何继续下去?

最佳答案

你不能用 vanilla 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 接口(interface)。用法:

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

应该打印类似的东西

1000
foo bar

在几秒钟的过程中。

关于javascript - setTimeout 与日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52119944/

相关文章:

python - 单独的日期时间字段以使用 Django 在 HTML 中单独显示日期和时间

javascript(在 Firefox 插件中)停止页面加载

javascript - 将缺失值添加到分组数据中

javascript - *ngIf 数组中存在值

python - 如何根据输入年份生成包含一年中各天的数据框?

javascript - 使用 setTimeout 循环播放视频

javascript - setTimeout 调用顺序

javascript - Node.js 中的 XML(使用 Javascript)

javascript - 防止在移动浏览器上滚动,而不防止输入焦点

php - 计算日期之间的天数但显示负 PHP