Go to the link above to understand why setTimeout()
ain't so great.
.currentTime
Property
This property is used by <audio>
and <video>
tags to get/set playback time in seconds. In the following demo it is used to get the time:
var t = this.currentTime;
timeupdate
Event
This event fires 4 times a second while an <audio>
or <video>
tag is playing. In the demo both a <video>
and <audio>
tag are registered to to the timeupdate
event:
video.addEventListener("timeupdate", tick);
timer.addEventListener("timeupdate", tock);
Setup
[controls]
Attribute
Added so the time can be reviewed as the demo runs, it's optional and recommended that it not be used in production.
<audio>
Tag
An <audio>
tag has been added as a timer, The attributes [muted]
and [autoplay]
are required:
<audio id='timer' src='https://od.lk/s/NzlfOTEwMzM5OV8/righteous.mp3' muted controls autoplay></audio>
Both tags will start playing and are listening to the timeupdate
event and will call a function at a predetermined time:
function tick(e) {
var t = this.currentTime;
if (t >= 3) {
this.pause();
video.removeEventListener("timeupdate", tick);
}
}
function tock(e) {
var t = this.currentTime;
if (t >= 5) {
video.play();
timer.removeEventListener("timeupdate", tock);
}
}
Basically when the <video>
and <audio>
tags are triggered every 250ms, they are calling those functions:
<video>
calls function tick()
if the playback time is 3 or more seconds it pauses.
to avoid constant triggering every 250ms, the eventListener is removed.
<audio>
calls function tock()
if the playback time is 5 or more seconds it will play the <video>
.
for the same reason as the <video>
, the eventListener is removed.
Demo
var video = document.getElementById('video');
var timer = document.getElementById('timer');
video.addEventListener("timeupdate", tick);
timer.addEventListener("timeupdate", tock);
function tick(e) {
var t = this.currentTime;
if (t >= 3) {
this.pause();
video.removeEventListener("timeupdate", tick);
}
}
function tock(e) {
var t = this.currentTime;
if (t >= 5) {
video.play();
timer.removeEventListener("timeupdate", tock);
}
}
<video id="video" playsinline muted loop controls autoplay width='300'>
<source src="https://html5demos.com/assets/dizzy.mp4" type="video/mp4"/>
</video>
<audio id='timer' src='https://od.lk/s/NzlfOTEwMzM5OV8/righteous.mp3' muted controls autoplay></audio>