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

268
Visualizações
setTimeout with prompt causing incrementing default value

Just experimenting with JS. I have found something I cant get my head around.

I have this code:

prompt('title', setTimeout(() => {
    return 'yes'
}, 1000));

When I first run it, it prints 2. But when I run it again, it prints 3.

But what is this counter, and why is it starting from 2? Where does the values come from? Why is it not returning yes?

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

0

When you call setTimeout the timeout is given a timeoutID (which can be later used to cancel it with clearTimeout). This timeoutID increments whenever a new timeout is made. When setting it as the default value for the prompt, it is stringified (causing the timeoutID to be returned).

The value starts from two because you've probably made a timeout before running the prompt.

Demonstration:

const first = setTimeout(() => {}, 1).toString()
const second = setTimeout(() => {}, 1).toString()
console.log(first, second)

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