[Solved] Can someone explain this piece of code to me

[ad_1]

It appears that variable is an array that stores references (URIs, or paths) to images, that is fed to the src attribute of an image element, <img>. The script simple does the following logic:

  • When the function is fired, it increments index by 1
  • If index is equal to the number of images, you return it to 0 (basically “cycling” through the array
  • You set the image source to the nth element of the variable array, by the index index

An intelligent guess would be that this is a image cycling function. When nextvariableClick is called it cycles through a list of images in the order they appear in the variable array.

Since the script is so simple, the best way to see what it does is to construct a functional code snippet:

// Define dummy image references
var variable = [
  'https://placehold.it/500x300/e41a1c/ffffff',
  'https://placehold.it/500x300/377eb8/ffffff',
  'https://placehold.it/500x300/4daf4a/ffffff',
  'https://placehold.it/500x300/984ea3/ffffff',
  'https://placehold.it/500x300/ff7f00/ffffff'
];

/* Start of code you have provided */
var index = 0;
var variableLen = variable.length;

function nextvariableClick() {
  index++;

  if (index == variableLen)
    index = 0;

  var image = document.getElementById('starting_light');
  image.src = variable[index];

}
/* End of code you have provided */

// We execute the function to start initialise it, and set a starting image
nextvariableClick();
window.setInterval(nextvariableClick, 1000);
<p>The function is called at runtime, and called every 1s. You should see cycling of image sources.</p>
<img id="starting_light" src="" />

0

[ad_2]

solved Can someone explain this piece of code to me