Doubt with a countdown in JS and HTML

Asked

Viewed 419 times

-2

I imagine that my doubt is a little silly, but I’m seriously half a day trying to solve this challenge that I proposed and unfortunately I could not, remembering that I am a good beginner.

Well, I decided to create a chronometer using JS, where the user inserts the time in an HTML input number, the JS receives the value, converts to number, then the if subtracts 1 of the value every 1000 milliseconds and displays in HTML.

It turns out that it works if I determine the fixed value in the time variable and put onload calling the js function in the body tag. But using the input number with onclick calling the function on the button it only displays the first value of the countdown and hangs. I’m stuck there. One more thing, I tried to put the input inside a form but in this case it only flashed the number and disappeared the value.

function contador(){
    let val = document.getElementById('valor');//essa variavel recebe o valor do form
    let time = Number(val.value);//essa variavel converte o valor recebido do form para numero
    
    if(time > 0){
        time = time -1;
        if(time == 0){
            time = "FIM!"
        }
    }

    tempo.innerText = time;
    setTimeout("contador()", 1000);
}
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contador regressivo!</title>
    <script src="main.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div>
        <h1>Digite abaixo um valor para o cronometro:</h1>
        <input type="number" name="valor" id="valor">
        <input type="submit" value="OK" onclick="contador()">
        <div id="tempo">Preparar!</div>
    </div>    
</body>
</html>

2 answers

2

The problem is that every second you are initiating the val again. It gives the impression that the loop is not working, but in fact it "always works with the same value"

See the difference Initiating only once (not a good solution, it’s just to highlight the problem):

var val; // Global apenas para ilustrar 
var time;

function inicia(){
    // VAMOS PEGAR O VALOR SO UMA VEZ
    val = document.getElementById('valor');//essa variavel recebe o valor do form
    time = Number(val.value);//essa variavel converte o valor recebido do form para numero
    setTimeout("contador()", 1000);
}

function contador(){
    // AGORA DECREMENTA, SEM PEGAR O VALOR INICIAL 
    if(time > 0){
        time = time -1;
        if(time == 0){
            time = "FIM!"
        }
    }

    tempo.innerText = time;
    setTimeout("contador()", 1000);
}
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contador regressivo!</title>
    <script src="main.js"></script>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div>
        <h1>Digite abaixo um valor para o cronometro:</h1>
        <input type="number" name="valor" id="valor">
        <input type="submit" value="OK" onclick="inicia()">
        <div id="tempo">Preparar!</div>
    </div>    
</body>
</html>

  • Man, vlw to answer, it sure will help in my studies!

-1

Well, to make the stopwatch would need to use the setInterval(), and you used the setTimeout().

The setTimeout() runs once after set time, while the setInterval() performs infinitely (or at least until you stop it with clearInterval()).

More information on Nodebr

Follow the correct code:

function iniciarContador(){
  const val = document.getElementById('valor');
  let time = Number(val.value) + 1;
  const contador = setInterval(() => {
    if (time > 0) 
      time = time - 1;
    else {
      time = "FIM!"
      console.log('Finished');
      clearInterval(contador);
    }
    tempo.innerText = time;
  }, 1000);
}

I hope I’ve helped.

  • Man, thank you worked right, really helped me in my studies, vlw!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.