Create a pure JS count

Asked

Viewed 76 times

0

I’m trying to make a code that when the page loads it starts counting and ends at the number I want,

I know how to stop the loop,

I tried using setTimeout()

function carregar (){

var c = 0;

setTimeout (function (){

document.getElementById("htmlp").innerHTML = c + "%";

c = c + 1;

}, 1000);
}

tried the same thing with setInterval() since it is a loop but it did not give in anything tbm

  • And where’s the number 60 that you want to finish counting?

  • I was going to explain there but I forgot,I already know how to stop the counting, I just don’t know how to start it. Every 1 second add +1 and go to 2 tlgd? That one I couldn’t do.

1 answer

0


It’s easier to use setInterval, because it’s a continuous timer, which you can stop it with clearInterval(). But you need to assign it to a variable. If you have inside a function, just call the function.

In the example below I put the time up to 10 seconds to illustrate:

document.addEventListener("DOMContentLoaded", function(){ // aguarda o DOM ser carregado
   var c = 0;
   var fim = 10;
   function carregar (){
     var contagem = setInterval(function(){
         if(c > fim){
            clearInterval(contagem);
         }else{
            document.getElementById("htmlp").innerHTML = c + "%";
            c = c + 1;
         }
      }, 1000);
   }
   carregar(); // inicia a função
});
<div id="htmlp"></div>

Browser other questions tagged

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