3

I can pause the video with globalThis.ytPlayerUtilsVideoTagPoolInstance.l[0].pause()

I can get the current time of the video with globalThis.ytPlayerUtilsVideoTagPoolInstance.l[0].currentTime

How do I trigger the pause automatically when the video reaches currentTime > 180 ?

Julien Reszka
  • 888
  • 12
  • 25

1 Answers1

5

An easy way is polling.

const player = globalThis.ytPlayerUtilsVideoTagPoolInstance.l[0]
setTimeout(function polling() {
    if (player.currentTime < 180) 
        setTimeout(polling, 1000)
    else
        player.pause()
}, 1000)

An alternative way:

const player = globalThis.ytPlayerUtilsVideoTagPoolInstance.l[0]
const timer = setInterval(() => { // no need of named function as no 'async recursion' is needed
    if (player.currentTime >= 180) {
        player.pause()
        clearInterval(timer)
    }
}, 1000)
obfish
  • 673
  • 4
  • 17
  • Thank you this works like requested. If I understand this correctly the function polling is calling itself inside of itself every second until it reaches the condition? Is this called a recursion? The fact that the the recursion is done every second is called "polling"? – Julien Reszka Dec 26 '18 at 14:27
  • 1
    I would call it async recursion, as it's actually not recusion. What the code does is checking if the condition is met, if not, schedule a check in the next second. Polling, in my opinion, means checking the condition at regular intervals. The code achieves similar functionality as `setInterval`. But if you choose to use `setInterval` to run a piece of code regularly you should remember to cancel it afer the condition met. Added an example with setInterval. The two styles should achieve the same goal. – obfish Dec 26 '18 at 15:42