-1

I don't know what i'm doing wrong. This code works perfectly:

// Check if the button has loaded every 10ms
    let isButtonAvailable = setInterval(function(){
        let button = document.querySelector("button[data-pid='0001380188021100000002']");
        console.log("button = " + button);

        if (button != null){
            button.style.zIndex = 10;
            button.click();
            clearInterval(isButtonAvailable);
            console.log("Button clicked")
        }
    }, 10);

But when I try to generalize the function called by setInterval(), it doesn't retry the code every 10 seconds, it only executes it once.

AddToCart_Selector = "button[data-pid='0001380188021100000002']"

function isAvailable(selector){
    console.log(selector);
    let button = document.querySelector(selector);
    console.log("button = " + button);
    console.log(isButtonAvailable);

    if (button != null){
        button.style.zIndex = 10;
        button.click();
        clearInterval(isButtonAvailable);
        console.log("Button clicked");        
    }
};

function main(){
    // Check if the button has loaded every 10ms
    isButtonAvailable = setInterval(isAvailable(AddToCart_Selector), 10);
}

main();

I don't really know how to pass isButtonAvailable as an id neither. Notice that I'm running this code inside a content script, it is executed with my chrome extension.

1 Answers1

0

setInterval should be passed with a function as the first argument. What you have done in the first example is correct, where you are passing the function definition as a callback for the setInterval to execute.

But in the generic function example, isAvailable(AddToCart_Selector) does not return a function, instead the isAvailable function is getting invoked while being passed to the setInterval.

Chaning your code to

isButtonAvailable = setInterval(() =>isAvailable(AddToCart_Selector), 10);

will work

Or using es5 syntax instead of arrow functions you can do the following

function isAvailable(selector){
   return function () {
    console.log(selector);
    let button = document.querySelector(selector);
    console.log("button = " + button);
    console.log(isButtonAvailable);

    if (button != null){
        button.style.zIndex = 10;
        button.click();
        clearInterval(isButtonAvailable);
        console.log("Button clicked");        
    }
   }

};

and then you can keep your setInterval invokation unchanged

setInterval(isAvailable(AddToCart_Selector), 10);
Kaushik
  • 921
  • 10
  • 18