Make function wait until element exists

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

    If you have access to the code that creates the canvas - simply call the function right there after the canvas is created.

    If you have no access to that code (eg. If it is a 3rd party code such as google maps) then what you could do is test for the existence in an interval:

    var checkExist = setInterval(function() {
       if ($('#the-canvas').length) {
          console.log("Exists!");
          clearInterval(checkExist);
       }
    }, 100); // check every 100ms
    

    But note - many times 3rd party code has an option to activate your code (by callback or event triggering) when it finishes to load. That may be where you can put your function. The interval solution is really a bad solution and should be used only if nothing else works.

提交回复
热议问题