While variable is not defined - wait While variable is not defined - wait jquery jquery

While variable is not defined - wait


The following will keep looking for someVariable until it is found. It checks every 0.25 seconds.

function waitForElement(){    if(typeof someVariable !== "undefined"){        //variable exists, do what you want    }    else{        setTimeout(waitForElement, 250);    }}


async, await implementation, improvement over @Toprak's answer

(async() => {    console.log("waiting for variable");    while(!window.hasOwnProperty("myVar")) // define the condition as you like        await new Promise(resolve => setTimeout(resolve, 1000));    console.log("variable is defined");})();console.log("above code doesn't block main function stack");

After revisiting the OP's question. There is actually a better way to implement what was intended: "variable set callback". Although the below code only works if the desired variable is encapsulated by an object (or window) instead of declared by let or var (I left the first answer because I was just doing improvement over existing answers without actually reading the original question):

let obj = encapsulatedObject || window;Object.defineProperty(obj, "myVar", {    configurable: true,    set(v){        Object.defineProperty(obj, "myVar", {            configurable: true, enumerable: true, writable: true, value: v });        console.log("window.myVar is defined");    }});    

see Object.definePropertyor use es6 proxy (which is probably overkill)


If you are looking for more: