Make function wait until element exists

前端 未结 11 1918
一向
一向 2020-11-28 17:40

I\'m trying to add a canvas over another canvas – how can I make this function wait to start until the first canvas is created?

function PaintObject(brush) {         


        
11条回答
  •  臣服心动
    2020-11-28 18:07

    Just use setTimeOut with recursion:

    waitUntilElementIsPresent(callback: () => void): void {
        if (!this.methodToCheckIfElementIsPresent()) {
            setTimeout(() => this.waitUntilElementIsPresent(callback), 500);
            return;
        }
        callback();
    }
    

    Usage:

    this.waitUntilElementIsPresent(() => console.log('Element is present!'));
    

    You can limit amount of attempts, so an error will be thrown when the element is not present after the limit:

    waitUntilElementIsPresent(callback: () => void, attempt: number = 0): void {
        const maxAttempts = 10;
        if (!this.methodToCheckIfElementIsPresent()) {
            attempt++;
            setTimeout(() => this.waitUntilElementIsPresent(callback, attempt), 500);
            return;
        } else if (attempt >= maxAttempts) {
            return;
        }
        callback();
    }
    

提交回复
热议问题