1
\$\begingroup\$

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.

t3chb0t
44.6k9 gold badges84 silver badges190 bronze badges
asked Feb 3, 2017 at 7:56
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

$(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.

answered Feb 3, 2017 at 12:10
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.