带日期对象的setTimeout [英] setTimeout with Date object

查看:74
本文介绍了带日期对象的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完成之前的任何给定时间还剩下多少时间。例如:计时器创建为1小时15分钟后,我使用命令显示剩余时间为45分钟。

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

我也尝试过使用Date对象执行此操作,但失败了。我怎么能继续这样做呢?

推荐答案

您不能用香草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();
  }
}

我希望他们一开始就为超时/间隔提供了面向对象的接口。用法:

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

应打印类似

的内容
1000
foo bar

在几秒钟内。

这篇关于带日期对象的setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆