Search code examples
javascriptclosurespause

Javascript loop clicker


I'm trying to make a javascript script running from the urlbar which for each row on a specific page clicks a button (allowing me to change a certain value), then edit that value, then click that button again to confirm. I'm running into a lot of trouble with simultaneity, as it seems to wait to do the first click 5000 ms even tho it's not being told to pause. didn't do the same when i tested the structure replacing things in between pauses with rando alerts

The reason for the pauses is bc there's a short loading animation during which I can't execute code. Anything glaringly wrong in this as-is? I know there's funky stuff w/ closure, but I thought by busywaiting i could get past it but its not.

function pause(milliseconds) {
    var dt = new Date();
    while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}
var q=document.getElementById("MainContent_gvProducts").children[0];
var l=q.children.length;

for(i=1;i<l;i++){
    q.children[i].children[0].children[0].click();
    pause(5000);
    var x=q.children[i].children[7].children[0].value;
    pause(1);
    x=math.round(x);
    pause(5000);
    q.children[i].children[0].children[0].click();
    pause(5000);
}

Solution

  • Your pause function seems very hacky. You should use setTimeout() instead, or something similar.

    If you can afford to use the latest JS tech, I'd recommand creating a promise with a timeout and using async/await, with something like this :

    async function pause(t = 1000) {
        return new Promise(resolve => {
            setTimeout(() => {
                resolve(true)
            }, t)
        })
    }
    
    for(i=1;i<l;i++){
        q.children[i].children[0].children[0].click();
        await pause(1000)
        var x=q.children[i].children[7].children[0].value;
        pause(1);
        x=math.round(x);
        await pause(5000);
        q.children[i].children[0].children[0].click();
        await pause(5000);
    }
    

    Note : your for loop must be placed in an async function.