user632770
user632770

Reputation:

Increment counter then reset that counter when reached a certain limit

I have 18 images from which I only wish to show 5 at any given time. I'm swapping out a new image every two seconds or so without showing duplicates. My HTML is hardcoded and pulling from an s3 bucket.

<img class="activeImg" src="img_1.jpg />  
<img src="img_2.jpg />
<img src="img_3.jpg />
<img src="img_4.jpg />
...
<img src="img_9.jpg />

I have a recursive setTimeout function that is calling moveCounter. moveCounter simply increments by 1, and replaces an image, every time it gets called. I hook into the element by adding the activeImg class to the img, then remove it before moving onto the next image.

The end goal is to count from 0...5, then back down 5...0, infinitely. All I'm doing is appending the value to an image name, thereby replacing images without showing a duplicate.

The problem is there is overlap and I'm getting a duplicate whenever counter === imgId.

// my recursive settimeout function fires off and adds an activeImg class to a random image element, then also fires off the replaceImage function

var counter   = 0;
var imgId     = 18;

  // increment counter and append new img
  function replaceImage(imgId){

     if (counter >= 9) {
      counter--;
      var imgId = imgId - counter;
    } else {
      counter++;
      var imgId = imgId - counter;
    }

    jQuery('.activeImg').attr('src', "image/img_"+imgId+".jpg");

    console.debug(counter)
    console.debug(imgId)

  }

I feel like there is a better way to approach this.

Upvotes: 1

Views: 4299

Answers (2)

Etheryte
Etheryte

Reputation: 25310

Seems that what you're looking for is a simple triangle wave.
You can generate one rather easily:

var a = 5;
var output = [];

for (var i = 0; i < 20; i++) {
  output.push(a - Math.abs(i % (2 * a) - a));
};
out.innerHTML = output;
<span id="out"></span>

Upvotes: 3

twinlakes
twinlakes

Reputation: 10228

var counter = 1;
var imgId = 18;

var op = 1; // the operation -- 1 for addition, -1 for subtraction


function replaceImage(imgId) {
  // increment or decrement the counter, depending
  // on the current direction
  counter += op;

  // use the original poster's snippet to set the active image
  var imgId0 = imgId + counter;
  $('.activeImg').attr('src', 'image/img_'+imgId0+'.jpg');

  // if we hit the upper or lower bound, reverse the direction
  // by flipping the operation
  if (counter === 5 || counter === 1)
    op *= -1;
}

Upvotes: 1

Related Questions