Reputation: 1327
I got a project that has a video that plays in a loop. Here is the html for the video tag:
<video playsinline autoplay muted loop id="myVid">
<source src="River.mp4" type="video/mp4">
</video>
I would like the video to pause after a delay, and I am trying to implement this using javascript. My javascript code:
function stopVideo() {
var vid = document.getElementById('myVid');
vid.pause();
}
setTimeout(stopVideo, 900);
This is not working. Any ideas why? Thank you.
---------------------------------------------------------------EDIT--------------------------------------------------------------
if it helps, the error console is giving me a message:
TypeError: null is not an object (evaluating 'vid.pause')
Upvotes: 0
Views: 957
Reputation:
Update based on new information from OP:
The null
means the element is not found by getElementById()
, indicating that the script is running before the DOM is built (ie. in the head tag).
Simply run the script code like this if in head:
window.onload = function() {
// code goes here
};
Or more the script tag to the bottom of the document before body close tag.
Old answer -
Before setting the timeout, make sure the video is actually playing. With a short delay of 900ms (0.9s) you can risk the timeout code triggers before the video has started playing.
To be sure the video is actually playing you can use events such as playing
and timeupdate
, but in timeupdate
is likely not accurate for this scenario, so one way around is to only trigger when playing
:
var vid = document.getElementById('myVid');
var reqId; // optional, prevents running more than one time
vid.addEventListener("playing", function() {
if (!reqId) reqId = setTimeout(stopVideo.bind(this), 2000);
});
function stopVideo() {
this.pause();
}
video {height:200px}
<video playsinline autoplay muted loop id="myVid">
<source src="//media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4">
</video>
Upvotes: 2
Reputation: 4523
It's working fine !
function stopVideo() {
var vid = document.getElementById('myVid');
vid.pause();
}
setTimeout(stopVideo, 5000);
<video playsinline autoplay muted loop id="myVid" width="400px" >
<source src="http://mazwai.com/system/posts/videos/000/000/123/original/victor_ciurus--5d_mark_iii_magic_lantern_14_bits_raw_video.mp4" type="video/mp4">
</video>
maybe, just increase the timer.
Upvotes: 1
Reputation: 21
I would try something like this:
setTimeout(function () {stopVideo()}, 900);
Upvotes: 0