使用JavaScript在视频结束前几秒运行一个函数

Run a function a few seconds before video ends using JavaScript

本文关键字:几秒 运行 函数 一个 JavaScript 视频 结束 使用      更新时间:2023-09-26

我有一个正在播放的视频。如何在视频结束前5秒调用函数?

我想在我开始播放视频时放一个计时器,问题是用户可以控制视频,并停止它并再次播放他想要的次数,所以计时器变得无效。

例子会很好!

——编辑这是一个代码的例子,我正在使用:

video = document.createElement("video");
    video.setAttribute("id", id);
    video.src = url;
    video.onended = function(e) {
        var playlistName = getPlaylistName();
        findNextSongToPlay(playlistName, playNextSong);
    };

我希望"onended"事件不是在最后被调用,而是在5秒之前被调用。所以我需要稍微改变一下…

再次感谢!

下面是一个演示

编辑:更新的演示。

window.onload=function(){
video = document.createElement("video");
    video.setAttribute("id", "Myvideo");
    video.setAttribute("controls", "controls");
    video.src = "http://www.w3schools.com/html/mov_bbb.mp4"; 
    video.addEventListener("timeupdate", myfunc,false);
    document.body.appendChild(video);  
}
function myfunc(){
	if(this.currentTime > this.duration-5){
		//Less than 5 seconds to go. Do something here.
//---- For Demo display purposes
document.getElementById('Example').innerHTML="Less than 5 seconds to go!";
//---------
	} //End Of If condition.
//---- For Demo display purposes
else{document.getElementById('Example').innerHTML="";}
//---------
}
<div id="Example"></div>

因为你的播放器是动态创建的,你可以使用:

video = document.createElement("video");
video.setAttribute("id", id);
video.src = url;
  //Add the event Listener
  video.addEventListener("timeupdate", myfunc,false);
  video.onended = function(e) {
    var playlistName = getPlaylistName();
    findNextSongToPlay(playlistName, playNextSong);
  };

调用这个函数

function myfunc(){
    if(this.currentTime > this.duration-5){
        //Do something here..
    }
}

如果你有任何问题,请在下面留言,我会尽快回复你。

我希望这对你有帮助。编码快乐!

HTML5播放器示例。

最多可以产生100毫秒的差异,而不是5秒。但是您可以调整脚本。

你可以粘贴下面的代码来试试:http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_video_all

<html>
<body>
    <video id="vid" width="320" height="240" controls>
        <source src="movie.mp4" type="video/mp4">
        <source src="movie.ogg" type="video/ogg">
        Your browser does not support the video tag.
    </video>
    <script>
        var callOnce = true;
        function monitorVideo() {
            if ((vid.duration - vid.currentTime) < 5)
                if (callOnce) {
                    myFunction();
                    callOnce = false;
                }
        }
        function myFunction() {
            console.log('5 seconds');
        }
        setInterval(monitorVideo, 100);
    </script>
</body>
</html>

请告诉我们您使用的是什么视频播放器

如果是自定义的,在部分写上id,表示距离视频有多远,然后写上

if (document.getElementById("bla").innerhtml === whatever 5 seconds before the end of the video is)
function();