Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

458
Visualizações
Convert seconds to milliseconds - javascript

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.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

  • Here is a better regex /(\d+) seconds?/ - the ? means the s 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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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
);
``

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda