I have just started to learn javascript today and i'm trying to work out how i can convert seconds to milliseconds.
I tried to find something that would help me but everything i find is converting milliseconds to minutes or hours.
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);
I have just started to learn javascript today and i'm trying to work out how i can convert seconds to milliseconds.
I tried to find something that would help me but everything i find is converting milliseconds to minutes or hours.
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);
I'm trying to extract the numbers from string and convert it to milliseconds for a setTimeout.
Share Improve this question asked Jan 11, 2022 at 12:36 teamgidoteamgido 231 gold badge1 silver badge3 bronze badges 3-
6
There are 1000ms to a second, so simply multiply the
number
by1000
– David Thomas Commented Jan 11, 2022 at 12:38 -
3
1s = 1000ms
, so why not to usesetTimeout(..., num * 1000)
? – Xeelley Commented Jan 11, 2022 at 12:38 - 1 Does this help you : stackoverflow./questions/43960824/… – Keivan Soleimani Commented Jan 11, 2022 at 12:39
3 Answers
Reset to default 2- Here is a better regex
/(\d+) seconds?/
- the?
means thes
is optional - 1 second is 1000 milliseconds as the word tells us
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);
Here is a countdown
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
);
``
If you are getting timestamps in seconds, convert that into milliseconds so that you can change in date format.
Example
let secToMilliSec = new Date(1551268800 * 1000);
let millToDate = new Date(secToMilliSec);
// Wed Feb 27 2019 17:30:00 GMT+0530 (India Standard Time)