2
function catGenerate(){
  var image = document.createElement('img');
  var division = document.getElementById('flexID');
  pic1 = 300;
  image.src = "https://placekitten.com/200/" + String(pic1) ;
  division.appendChild(image);
  pic1++;
}

I want to add pic1 value by one when once the function is used, how can I do it?

MorKadosh
  • 5,846
  • 3
  • 25
  • 37

1 Answers1

0

I wouldn't encourage using global variables. This is a classic closure example, your generator function should return a function like this:

function catGenerator() {
  // internal state
  let pic1 = 300;

  return function doSomething() {
    var image = document.createElement('img');
    var division = document.getElementById('flexID');
    image.src = "https://placekitten.com/200/" + pic1;
    division.appendChild(image);
    pic1 += 1;
  }
}

Then use it like this:

const generator = catGenerator();
generator(); // pic1 = 300
generator(); // pic1 = 301
... etc

This is a good blog post that explains how this works: https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4

VladNeacsu
  • 1,268
  • 16
  • 33