Make function wait until element exists

前端 未结 11 1894
一向
一向 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

    Is better to relay in requestAnimationFrame than in a setTimeout. this is my solution in es6 modules and using Promises.

    es6, modules and promises:

    // onElementReady.js
    const onElementReady = $element => (
      new Promise((resolve) => {
        const waitForElement = () => {
          if ($element) {
            resolve($element);
          } else {
            window.requestAnimationFrame(waitForElement);
          }
        };
        waitForElement();
      })
    );
    
    export default onElementReady;
    
    // in your app
    import onElementReady from './onElementReady';
    
    const $someElement = document.querySelector('.some-className');
    onElementReady($someElement)
      .then(() => {
        // your element is ready
      }
    

    plain js and promises:

    var onElementReady = function($element) {
      return new Promise((resolve) => {
        var waitForElement = function() {
          if ($element) {
            resolve($element);
          } else {
            window.requestAnimationFrame(waitForElement);
          }
        };
        waitForElement();
      })
    };
    
    var $someElement = document.querySelector('.some-className');
    onElementReady($someElement)
      .then(() => {
        // your element is ready
      });
    

提交回复
热议问题