Make function wait until element exists

前端 未结 11 1924
一向
一向 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:03

    A more modern approach to waiting for elements:

    while(!document.querySelector(".my-selector")) {
      await new Promise(r => setTimeout(r, 500));
    }
    // now the element is loaded
    

    Note that this code would need to be wrapped in an async function.

提交回复
热议问题