我正在根据用户输入创建超时,输入格式为:1min
或 2h
,并通过以下方式确定是一分钟还是一小时代码;
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/