当其他活动时停止DOM事件?

时间:2017-05-10 21:11:38

标签: javascript

我用JS制作自己的视频播放器。我想知道如何只在timeupdate监听器不活动时才运行input的内容? document.getElementById('progress')也是范围滑块的输入类型。 input侦听器代码仅在您主动拖动它时运行,并且只有在您松开滑块后才停止运行偶数。

<div class="center">
    <video id="video" src="video1.mp4" width="100%" preload="metadata" autoplay controls muted></video>
    <input id="progress" type="range" min="0" max="100" value="0" width="100%">
</div>


document.addEventListener('DOMContentLoaded', function() {

    var video = document.getElementById('video')
    var progress = document.getElementById('progress')

    video.addEventListener('loadedmetadata', function() {
        progress.max = video.duration
    })

    video.addEventListener('timeupdate', function() {
        progress.value = video.currentTime
    })

    progress.addEventListener('change', function() {
       var seek = video.duration * (progress.value / 100)
       video.currentTime = seek
    })

    progress.addEventListener('input', function() {
      console.log('woo')
    })

})

1 个答案:

答案 0 :(得分:0)

您可以使用简化的debounce功能。

去抖功能确保你只调用一个目标函数,除非去抖函数在最后N毫秒内调用了 not

在您的情况下,只要调用timeupdate,就要禁用input

// Initial state: 'timeupdate' is enabled
var disableTimeupdate = false;

video.addEventListener('timeupdate', function() {
    // don't do anything if 'timeupdate' is disabled
    if (disableTimeupdate) return;
    progress.value = video.currentTime
})

// Define debounced function.
// It will be called in the 'input' event handler
var debounceEnableTimeupdate = debounce(function() { 
    disableTimeupdate = false; 
}, 1000);

progress.addEventListener('input', function() {
  // Disable the timeupdate event
  disableTimeupdate = true;
  // Re-enable it if 'input' has not been triggered in the past second
  debounceEnableTimeupdate();
})

有关debounce on this page

的更多详情