I'm trying to show to the user that the page is reading/loading by creating an animation of dots.

Here is the HTML:

<div id="dot">Authenticating</div>
<hr>
<button id="run">
Run It
</button>
<button id="stop">
Stop
</button>


And here is the script:

$(document).ready(function(){ var interval; function countdown(){ counter = 1; interval = setInterval(function(){ if(counter > 0 && counter < 4){$("#dot").append('.');
} else {
counter = 0;
$("#dot").text('Authenticating'); } counter += 1; },1000); }$("#run").click(function(){
countdown();
})

$("#stop").click(function(){$("#dot").text('Authenticating');
clearInterval(interval);
})

})


Any better way to implement it?

Check fiddle here.

$(document).ready(function(){ var interval; function startIndicator(){ stopIndicator(); dotCount = 1; interval = setInterval(function(){$("#dots").text('.'.repeat(dotCount));

dotCount++;
if(dotCount > 3){
dotCount = 0;
}

},1000);
}

function stopIndicator(){
clearInterval(interval);
dotCount = 0;
$("#dots").text(''); }$("#run").click(startIndicator);

\$("#stop").click(stopIndicator);

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="progress">Authenticating<span id="dots"></span></div>
<hr>
<button id="run">
Run It
</button>
<button id="stop">
Stop
</button>

This improves:

• Original code allowed multiple timers set causing issues
• String "Authenticating" not repeated and confined to HTML
• Slightly cleaner conditions
• Renamed countdown to indicator because it's not really a countdown
• WARNING: .repeat maybe only works in quite modern browsers

Note: If you want to hide the "Authentication" text as well, just add CSS to hide the .progress div where appropriate.

One alternative approach that will probably give less and simpler code, at the cost of user's CPU, is to make the dots update all the time and simply toggle the visibility of #dots or .progress.