Reputation: 437
Trying to make the most simple gallery. There is a button that turns the image <button class = "play-pause">Play</ button>
. Clicking on it starts setInterval
, but when pressed again need to have it stopped. How can this be done?
Here's a link to the sandbox: http://jsfiddle.net/eL31q3eq/
My attempt:
document.querySelector('.play-pause').addEventListener('click', function() {
if(timer == null) clearInterval(timer);
this.innerHTML = "Pause";
timer = setInterval(function() {
i = (i < images.length - 1) ? ++i : 0;
img.src = images[i];
}, 1000);
timer = null;
});
Upvotes: 0
Views: 56
Reputation: 2312
The issue is that clearInterval
takes the interval object as an argument, and clears it. You're setting timer
to null, so you're asking it to clear null
which means it won't do anything.
WindowTimer.clearInterval - MDN
You need to use another variables to check the status of the play/pause button.
document.querySelector('.play-pause').addEventListener('click', function() {
if(playing === true) {
this.innerHTML = 'Play';
clearInterval(timer);
playing = false;
return;
}
this.innerHTML = "Pause";
timer = setInterval(function() {
i = (i < images.length - 1) ? ++i : 0;
img.src = images[i];
}, 1000);
playing = true;
});
http://jsfiddle.net/eL31q3eq/2/
Upvotes: 1
Reputation: 323
You are discarding the variable you need to stop the slideshow - solution here.
Don't initialize your timer variable either.
document.querySelector('.play-pause').addEventListener('click', function() {
if (timer) {
clearInterval(timer);
this.innerHTML = "Play";
}
else {
this.innerHTML = "Pause";
timer = setInterval(function() {
i = (i < images.length - 1) ? ++i : 0;
img.src = images[i];
}, 1000);
}
});
Upvotes: 2