0

I have to find a button when it will appear. In order to do that I use setInterval. When it finds this button, it gives to my variable needed value. I check it inside the setTimeout, but after setTimeout(outside these method) my global variable became as before setTimeout. How to fix that?

let foundValue;
function findById(id) {
  let interval = setInterval(() => {
    if (document.getElementById(id)){
      let foundValue = document.getElementById(id);
      clearInterval(interval);
    }
  }, 1000);
  return foundValue;
}
teimurjan
  • 1,875
  • 9
  • 18

1 Answers1

1

It's because you're re-declaring foundValue inside setInterval so you should remove the second let, for example:

let foundValue;
function findById(id) {
  let interval = setInterval(() => {
    if (document.getElementById(id)){
      foundValue = document.getElementById(id);
      clearInterval(interval);
    }
  }, 1000);
  return foundValue;
}
phpchap
  • 382
  • 2
  • 7
  • I deleted these let but nothing happened – teimurjan Nov 07 '16 at 17:27
  • It's working for me as follows `console.log(foundInterval) // is undefined` then `findById('element_id')` then `console.log(foundInterval) // contains element` – phpchap Nov 07 '16 at 18:18