For some time already I'm struggling with following code:
$(document).ready(function(){
keyBind();
});
var set = [];
var start = 0;
var total = 3;
var timeout = 1000;
function displayImages(i, total){
var pixBox = $('#picture-box');
var imgPre = 'resources/exhibit-';
var imgExt = '.png';
var sndExt = '.wav';
var imgSrc = '<img class="image" src="' + imgPre + i + imgExt +'">';
var sndSrc = new Audio(imgPre + i + sndExt);
var magic = ((i+1)%total) + ',' + total;
sndSrc.play();
pixBox.append(imgSrc);
var sT = setTimeout('displayImages(' + magic + ')', timeout);
set.push(sT);
if(sT >= total+1){
sndSrc.pause();
}
if(sT === total+1){
clearTimeout(sT);
// $('img').remove();
$('img:not(:last-child)').remove();
}
return false;
}
function keyBind(){
$(document).keydown(function(e) {
switch (e.which) {
case 75: //k
displayImages(start, total);
break;
case 80: //p
clearTimeout(set);
break;
default:
return;
}
e.preventDefault();
});
}
It's a kind of very primitive slideshow with accompanying sound files for each picture/slide. As you can see, it's controlled by keyboard input (keyBind
function). And it all works fine, but only for the first time. When I trigger it fresh, timeOut
function is doing it job and both if
statements (first responsible for cutting the sound after the last file, second responsible for wrapping images back to first one after last is displayed) are fireing up and all is well.
That is, until I want to restart the sequence again, without refreshing. If I do that, soundfiles are going mute and the image sequence turns into an endless loop.
I've already tried dividing start and stop of sequence in separate functions, I tried to clear the div and reset the sound at the start of sequence and I did tried reseting the timeOut
at the beggining too. All to no avail.
Do you, good and dear people of SO, have any idea what's wrong with my code and can shed some light on it? It's gonna be a lifesaver.
EDIT
It looks like setTimeout(sT)
is not working. I've put a console.log
after it and sT
is not 0, it still has ID of last iteration. What may be the cause? What am I doing wrong?