我今天刚刚开始学习 javascript,我正在尝试弄清楚如何将秒转换为毫秒。
我试图找到一些对我有帮助的东西,但我找到的所有东西都是将毫秒转换为分钟或小时。
let str = 'You must wait 140 seconds before changing hands';
let timer = 0;
let num = str.match(/\d/g).join("");
timer = num;
console.log(timer);
setTimeout(() => {
console.log('time done')
}, timer);
我正在尝试从字符串中提取数字并将其转换为毫秒以设置超时。
/(\d+) seconds?/
- ?
表示 s
是可选的let str = 'You must wait 140 seconds before changing hands';
let timer = str.match(/(\d+) seconds?/)[1]*1000; // grab the captured number and multiply by 1000
console.log(timer)
setTimeout(() => {
console.log('time done')
}, timer);
这里是倒计时
let str = 'You must wait 10 seconds before changing hands';
const span = document.getElementById("timer");
let tId = setInterval(() => {
let timeLeft = +str.match(/(\d+) seconds?/)[1]; // optional s on seconds
if (timeLeft <= 1) {
str = "Time's up";
clearInterval(tId);
}
else str = str.replace(/\d+ seconds?/,`${--timeLeft} second${timeLeft == 1 ? "" : "s"}`)
span.innerHTML = str;
}, 1000);
<span id="timer"></span>
let str = 'You must wait 140 seconds before changing hands';
let seconds = /\d+/.exec(str)[0];
// milliseconds = seconds * 1000;
const ms = seconds * 1000;
setTimeout(
() => {// doSomething},
ms
);
``
如果您获取的时间戳以秒为单位,请将其转换为毫秒,以便您可以更改日期格式。
示例
let secToMilliSec = new Date(1551268800 * 1000);
let millToDate = new Date(secToMilliSec);
// Wed Feb 27 2019 17:30:00 GMT+0530 (India Standard Time)