Search code examples
javascriptfor-looponclickclickdelay

JavaScript Automated Clicking


So, here's my issue.

I need to write a script to be run in the console (or via Greasemonkey) to automate clicking of certain links to check their output.

Each time one of these links is clicked, they essentially generate an image in a flash container to the left. The goal here is to be able to automate this so that the QC technicians do not have to click each of these thumbnails themselves.

Needless to say, there needs to be a delay between each "click" event and the next so that the user can view the large image and make sure it is okay.

Here is my script thus far:

function pausecomp(ms) {
    ms = ms + new Date().getTime();
    while (new Date() < ms){}
} 

var itemlist, totalnumber, i;
itemlist = document.getElementsByClassName("image");
totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""));
for(i = 0; i < totalnumber; i = i + 1) {
    console.log(i);
    itemlist[i].childNodes[1].click();
    pausecomp(3000);
}

Now, totalnumber gets me the total number of thumbnails, obviously, and then itemlist is a list of get-able elements so I can access the link itself.

If I run itemlist[0].childNodes[1].click() it works just fine. Same with 1, 2, 3, etc. However, in the loop, it does nothing and it simply crashes both Firefox and IE. I don't need cross-browser capability, but I'm confused.


Solution

  • People were correct with SetInterval.

    For the record, here's the completed code:

    /*global console, document, clearInterval, setInterval*/
    var itemlist, totalnumber, i, counter;
    i = 0;
    
    function findmepeterpan() {
        "use strict";
        console.log("Currently viewing " + (i + 1));
        itemlist[i].scrollIntoView(true);
        document.getElementById("headline").scrollIntoView(true);
        itemlist[i].style.borderColor = "red";
        itemlist[i].style.borderWidth = "thick";
        itemlist[i].childNodes[1].click();
        i = i + 1;
        if (i === totalnumber) {
            clearInterval(counter);
            console.log("And we're done! Hope you enjoyed it!");
        }
    }
    
    function keepitup() {
        "use strict";
        if (i !== 0) {
            itemlist[i - 1].style.borderColor = "transparent";
            itemlist[i - 1].style.borderWidth = "medium";
        }
        findmepeterpan();
    }
    
    itemlist = document.getElementsByClassName("image");
    totalnumber = parseInt(document.getElementById("quickNavImage").childNodes[3].firstChild.firstChild.nodeValue.replace(/[0-9]* of /, ""), 10);
    counter = setInterval(keepitup, 1500);