PlayerSdk wrap init to get the PlayerSdk class using a promise

by marcelow

HTML

<div class="playerWrap">
  <iframe id="wallaPlayer" frameborder="0" allowfullscreen="allowfullscreen" src="https://www.walla.co.il/player.html?player=walla&media=3265142&disableAds=true"></iframe>
</div>
<style>
  .playerWrap {
    position: relative;
  }

  .playerWrap::before {
    content: "";
    display: block;
    padding-top: 56.25%;
  }

  .playerWrap>iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
  }

</style>
<script>
  const getPlayerSdkPromise = () => {
    return new Promise((resolve, reject) => {
      window.playerInit = window.playerInit || [];
      if (window.PlayerSdk) {
        return resolve(window.PlayerSdk)
      }
      window.playerInit.push(() => {
        return resolve(PlayerSdk);
      });
      const timeoutTime = Date.now() + 5000 // reject if the PlayerSdk is not available withing 5 seconds
      const interval = setInterval(() => {
        if (window.PlayerSdk) {
          clearInterval(interval);
        } else if (Date.now() > timeoutTime) {
          clearInterval(interval);
          window.playerInit = [];
          reject('PlayerSdk timeout')
        }
      }, 100);
    });
  };
  getPlayerSdkPromise().then((PlayerSdk) => {
    const playerSdk = new PlayerSdk();
    playerSdk.init('#wallaPlayer');
    playerSdk.on('FirstProgress', (data) => {
      console.log('playerdemo timeupdate!!!!', data);
    });
    playerSdk.on('ended', (data) => {
      console.log('playerdemo playback ended!!!!!', data);
    });
  }).catch((error) => console.error(error));

</script>
<script src="https://www.walla.co.il/playerSdk_walla.js"></script>