Search code examples
javascriptclicksettimeoutsetintervalauto

Auto click of the list items periodically by Javascript


I have a page that has a list where I need to click automatically of all items serially and periodically. Also, I have a button that needs to be clicked after clicking every item. And after all, it will repeat when it will finish clicking all items. I wrote a Javascript code and it works that I desired. But the problem is that it's a very lengthy code since I've about 170 items on the list. The code sample only for 7 items is given below:

setInterval(function(){ 

var btn = document.getElementById("ember331");

var span_0 = document.getElementsByClassName("ember-view")[0];
setTimeout(function(){
span_0.scrollIntoView();
document.getElementById("ember104").scrollIntoView();
span_0.click(); }, 5000);

setTimeout(function(){
btn.click(); }, 8000);

var span_1 = document.getElementsByClassName("ember-view")[1];
setTimeout(function(){
span_1.click(); }, 13000);

setTimeout(function(){
btn.click(); }, 16000);

var span_2 = document.getElementsByClassName("ember-view")[2];
setTimeout(function(){
span_2.click(); }, 21000);

setTimeout(function(){
btn.click(); }, 24000);

var span_3 = document.getElementsByClassName("ember-view")[3];
setTimeout(function(){
span_3.click(); }, 290000);

setTimeout(function(){
btn.click(); }, 32000);

var span_4 = document.getElementsByClassName("ember-view")[4];
setTimeout(function(){
span_4.click(); }, 37000);

setTimeout(function(){
btn.click(); }, 40000);

var span_5 = document.getElementsByClassName("ember-view")[5];
setTimeout(function(){
span_5.click(); }, 450000);

setTimeout(function(){
btn.click(); }, 48000);

var span_6 = document.getElementsByClassName("ember-view")[6];
setTimeout(function(){
span_6.click(); }, 450000);

setTimeout(function(){
btn.click(); }, 48000);


 }, 53000);

You may already notice that it is so long only for 7 items.

So, can it be possible to write it in short and alternative ways??


Solution

  • Consider using an async function instead. Whenever you need to delay, await a Promise that resolves after the desired number of milliseconds. Then you can just loop over the .ember-views and await when needed before clicking:

    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    const btn = document.getElementById("ember331");
    // use a recursive setTimeout, not setInterval,
    // so you don't have to hard-code the interval time
    setTimeout(async function timeoutCallback() {
      await delay(2000);
      for (const emberView of document.querySelectorAll('.ember-view')) {
        await delay(3000);
        emberView.scrollIntoView();
        emberView.click();
        await delay(3000);
        btn.click();
      }
      setTimeout(timeoutCallback, 5000);
    });