Search code examples
youtubejwplayerjwplayer7

JW Player 7 pause on precise time


I'm playing around with YouTube embed video. I want the player to pause on third second. Code below:

playerInstance.on('time', function(x) {
    if (x.position === 3){
        playerInstance.pause();
    }
});

But it dosen't work everytime. Sometimes it works and sometimes it doesn't. It's totally random. Why?


Solution

  • Depending on the media type being played and other events hooked to the JW player instance, the "onTime" event is fired multiple times a second, and is reported to numerous decimal places.

    It is therefore very unlikely that the "position" will ever be exactly 3 (which is what you are effectively saying with the following: '==' & '===').

    It would be more robust to use '>=':

    playerInstance.on('time', function(x) {
        if (x.position >= 3){
            playerInstance.pause();
        }
    });
    

    However, this as-is would mean the player would not be able to play beyond 3 seconds, so depending on your requirements, you may also need to include additional logic to cater for the following:

    • continuing to play after the pause point
    • what to do if the user seeks beyond 3 seconds
    • seeking back and then reaching the pause point a second time
    • etc...

    Probably a better solution would be to convert the "position" to an integer value and do a direct comparison. That means you wouldn't need logic to handle progressing past the pause point. You would however need logic to ensure it was only paused once at the pause point. The following caters for this:

    playerInstance.on('time', function(x){
        if(parseInt(x.position,10)===3){
            if(!playerInstance["pauseOnce"]){
                playerInstance["pauseOnce"]=true;
                playerInstance.pause();
            }
        }else{
            playerInstance["pauseOnce"]=false;
        }
    });