【问题标题】:Pause a youtube video from the chrome console after it reaches 3 minutes在 3 分钟后暂停来自 chrome 控制台的 youtube 视频
【发布时间】:2018-12-26 14:01:24
【问题描述】:

我可以暂停视频 globalThis.ytPlayerUtilsVideoTagPoolInstance.l[0].pause()

我可以通过globalThis.ytPlayerUtilsVideoTagPoolInstance.l[0].currentTime获取视频的当前时间

视频到达currentTime > 180时如何自动触发暂停?

【问题讨论】:

    标签: javascript google-chrome-devtools youtube-javascript-api google-chrome-console


    【解决方案1】:

    一种简单的方法是轮询。

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

    另一种方式:

    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)
    

    【讨论】:

    • 感谢您按要求完成这项工作。如果我理解正确,函数轮询每秒都会在自身内部调用自身,直到达到条件?这叫递归吗?每秒执行一次递归的事实称为“轮询”?
    • 我称之为异步递归,因为它实际上不是递归。代码所做的是检查是否满足条件,如果不满足,则在下一秒安排检查。在我看来,轮询意味着定期检查情况。该代码实现了与setInterval 类似的功能。但是如果您选择使用setInterval 定期运行一段代码,您应该记住在条件满足后取消它。添加了一个带有 setInterval 的示例。这两种风格应该达到相同的目标。
    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 1970-01-01
    • 2017-04-11
    • 2014-11-06
    • 1970-01-01
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    相关资源
    最近更新 更多