How can I stop a specific setTimeout
loop using clearTimeout(myVar)
?
I am using multiple callbacks that include unique audio file names as parameters. When the function triggerAudio
receives a callback, it starts an audio file loop. The issue is that if I have started more than one setTimeout audio loop (ie, multiple sounds are playing at the same time), how can I stop a specific loop/sound/setTimout? Said another way, how can I choose which audio loop is stopped?
// starts 1.wav looping
(function loopStart() {
triggerAudio('1.wav');
}());
// starts 2.wav looping
(function loopStart() {
triggerAudio('2.wav');
}());
// stops one of the audio loops after 5 seconds
setTimeout(function() {
(function loopStop() {
clearTimeout(myVar); // not sure how to control which function this will stop/clear
}());
}, 5000);
// main functino that loops the files noted by the callbacks
function triggerAudio(soundFileName) {
// code that starts and loops audio file with setTimeout loop
}
I suspect I need to somehow name (I'm not sure of the terminology) the setTimeout
started by each callback so that I can stop that one? But, I'm not sure how to approach this.
var timeout = setTimeout(function() {...}, 1000);
then you can call clearTimeout(timeout) to clear your timeout function. For your scenario, you can just use a variable to keep the timeout object, so when you try to play the video, you can validate the timeout object and clear it if it is not undefined, like this:
if (timeout) clearTimeout(timeout)
to stop the previous timeout
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.