1

I have the following code:

for (z=0;z<7;z++) {
  x = Math.floor((Math.random() * 7));
  //I am pulling some class names from an array here
  var element = document.querySelector("." + map[x]);
  //element.click();            
  console.log('No timeout ', x);

  setTimeout(function() {
    console.log('timeout ', x);
    element.click();
  }, 200);
}

Essentially, I am expecting to click a variety of random elements, however, when adding the click method in the setTimeOut function, I discovered that it clicked the same element. But when executed in the main code, it worked as expected, just a lot faster than I want!

To test this, I added some logs. The No timeout log produces numbers: 1,2,3,4,5,6,7 while the timeout log produces numbers: 7,7,7,7,7,7,7 (the last number from the No timeout log...

This explains why the same element is being clicked, I am not 100% sure why this is the case though?

Rojo
  • 2,749
  • 1
  • 13
  • 34
HappyCoder
  • 5,985
  • 6
  • 42
  • 73

2 Answers2

2

Javascript resolves the timeouts AFTER The loop has already ran. Knowing this, we'd want to bind the value x to the anonymous function and pass it through like this:

for (z = 0; z < 7; z++) {
  x = Math.floor((Math.random() * 26));
  //element.click();            
  console.log('No timeout ', x);

  setTimeout(function(x) {
    console.log('timeout ', x);
  }.bind(this, x), 200);
}

Hope this helps

Derek Pollard
  • 6,953
  • 6
  • 39
  • 59
  • 1
    Thank you - this helped me solve the problem, I did not use this exactly but it lead me to the best solution for the method. – HappyCoder Sep 26 '19 at 10:25
2

setTimeout function is asynchronous, so basically what is happening that loop will iterate until the end before setTimeout is called, so it will set z to 7. You will need something like this to achieve what you want:

(function loop(z, length) {
  if (z>= length) {
    return;
  }
  setTimeout(function() {
    console.log('timeout ', z);
    element.click();
  }, 200);
 })(1, 7);

That is called IIFE pattern, you can read more about it HERE

More detailed explanation about your particular problem you can find HERE

N. Djokic
  • 898
  • 1
  • 6
  • 19