Exponential Loop

by Marius Jopen

HTML

<div id="result"></div>

<div id="counter">
  move
</div>

<div id="target">
  Click here
</div>

<div class="images">
  <img id="img_1" src="https://i.redd.it/vcgfso7treez.jpg">
  <img id="img_2" src="https://i.redd.it/w15bx1mmogez.jpg">
  <img id="img_3" src="https://i.redd.it/ybivd2jg1fez.jpg">
  <img id="img_4" src="https://c2.staticflickr.com/6/5578/14662229426_75558b7d19_b.jpg">
  <img id="img_5" src="https://i.redd.it/ldksuu9g5cez.jpg">
  <img id="img_6" src="https://i.redd.it/1cxyp7rku9ez.jpg">
  <img id="img_7" src="https://i.redd.it/8wp45uwg0cez.jpg">
  <img id="img_8" src="https://i.redd.it/da1auusd5aez.jpg">
</div>

CSS

#counter {
  height: 100px;
  width: 100px;
}

#target {
  height: 100px;
  width: 100px;
  background-color: yellow;
  position: absolute;
  top: 0px;
  right: 0px;
}

.images img {
  display: none;
  height: 400px;
  width: auto;
}

JavaScript

var animationLength = 20000,
  counter = 0,
  counterEnd = 100,
  countInterval = animationLength / counterEnd, // 20 ms,
  a = 1.05,
  summatory = 0;

function action() {

  var imagecount = $(".images img").length,
    	random = Math.floor(Math.random() * imagecount) + 1;

 	$('.images img').css("display", "none");
  $('#img_' + random).css("display", "block");

  $('#counter').text(random);
  $('#result').text(counter++);

  $("#target").click(function() {
    counter = 0;
    summatory = 0;
  });

}

function animate() {

  action();

  if (counter <= counterEnd) {
    var newInterval = (animationLength - summatory) / ((a - Math.pow(a, -(counterEnd - 1))) / (a - 1))

    summatory += newInterval;
    countInterval = newInterval;
    setTimeout(animate, newInterval);
  }

  if (counter == counterEnd) {
    counter = 0;
    summatory = 0;
  }

}



animate();