Loop function

by Farzad Cyrus

HTML

<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="progress">
  <span class="progress-pecentage"></span>
</div>

<div class="container">
</div>

<div class="finish">
</div>

CSS

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  font-size: 12px;
  font-family:Arial;
  line-height: 24px;
}

.progress {
  display: block;
  height: 48px;
  width: 400px;
  padding: 8px;
  position: relative;
  background-color:#cccccc;
  color:#ffffff;
  margin-bottom: 16px;
}

.progress-pecentage {
  display: inline-block;
  height: 100%;
  width: auto;
  position: relative;
  background-color:#114477;
  padding: 0 16px;
  line-height: 32px;
}

JavaScript

function intervalLoop(options) {

      var totalTime = options.totalTime,
        elapsedTime = 0,
          delay = options.delay,

        onInit = options.onInit || null,
        onFinish = options.onFinish || null,

        percentage;

      setInterval(function () {

        percentage = (elapsedTime / totalTime) * 100;


        // ON START
        if (elapsedTime < totalTime) {

          if (onInit != null) {
            // THIS SHOULD RUN CONTINUOUSLY UNTIL THE TOTAL TIME IS REACHED, 
            // THE PERCENTAGE THAT HAS BEEN COMPLETED SHOULD BE PRINTED
            onInit(percentage);
          }

          // ON FINISH
        } else if (elapsedTime == totalTime) {
          if (onFinish != null) {
            setTimeout(function () {
              // THIS CODE SHOULD RUN FOR ONLY ONCE, WHEN THE TOTAL TIME IS REACHED
              onFinish();

            }, delay);
          }

          // RESET
        } else if (elapsedTime > totalTime) {
          elapsedTime = 0;

        }
        elapsedTime++;

      }, 1000); // THIS SHOULD BE CALCULATED BASED ON OUR TOTAL TIME
    }


    //AND HERE IS THE USAGE

var $progressPercentage = $('.progress-pecentage'),
		$container = $('.container'),
    $finish = $('.finish');





    intervalLoop({

      totalTime: 5, // 5 SECONDS IS THE TOTAL TIME WE HAVE
      delay: 5, // 5 SECONDS IS THE DELAY FOR BETWEEN THE onInit and onFinish

      onInit: function (percentage) {

        // SHOULD RUN CONTINUOUSLY 
        $progressPercentage.html(percentage + '%').css({'width' : percentage + '%'});

      },
      onFinish: function () {

        // SHOULD RUN ONCE AT THE END OF THE ENTIRE LOOP
        $finish.html('Reload some AJAX stuff or change something on the page.<br>Loop finished! Restart again :)');
        setTimeout(function(){
        $finish.html('');
          },2000);

      }
    });