Search code examples
javascriptloopsgoogle-chrome-extension

simple javascript loop click button


I am a beginner in javascript and I want to do a loop where it clicks a button, then when another button appears on the page, the loop stops and clicks the button that appeared. (After clicking a random number of times the "loop" button, you can click the "appeared" button) Thanks so much for your help

Button to loop: document.getElementById('loop').click();

Button button that appeared: document.getElementById('appeared').click();


Solution

  • If the "appeared" element is undefined, then the clicked element will be "loop", otherwise it will be "appeared". I added a delay of 100 ms otherwise the browser may crash.

    (function loop() {
      setTimeout(function() {
        const appeared = document.getElementById('appeared')
        document.getElementById(appeared?'appeared':'loop').click()
        loop()
      }, 100)
    })()