vendredi 1 mars 2019

Unusual counting sequence in jQuery

This is my first post. Please be kind.

My console log is showing that my "num" variable is not increasing by 1 each time the function runs. See screenshot:

Image of my console messages

I want num to increase by 1 each time so I can find the new image url and change the background image in sequence using the [num] index: 0, 1, 2 then 3. I also want to reset the num value to 0 once it exceeds 3.

Why is my code generating a random series of values for my num variable?

var num = 0

var image1 = 'image1.jpg'
var image2 = 'image2.jpg'
var image3 = 'image3.jpg'
var image4 = 'image4.jpg'

var images = [image1, image2, image3, image4]

var interval = setInterval(function() {

  if (num < images.length - 1) {
    num = num + 1
  } else {
    num = 0
  }

  $('.hero').css('background-image', 'url(' + images[num] + ')')

  console.log(num)

}, 5000) 

The code runs and I almost have my desired effect, but I don't understand why my index isn't increasing by one each time.

Any help is really appreciated.

Aucun commentaire:

Enregistrer un commentaire