Reputation: 2126
I have created simple script with setInterval function and it is working fine on first button click, but if I click my button couple of times my interval is queued up! I have tried to solve this using one function with Jquery but then I cannot set my Intereval again.
Is there a way to prevent this? Thank you!!
Fiddle example
My code:
var changeClass=function(){
if($('ul li.active').length==0){
$('ul li:first').addClass('active');
}
else if($('.active').next().length==0){
$('.active').removeClass('active');
$('ul li:first').addClass('active');
}
else{
$('.active').removeClass('active').next('li').addClass('active')
}
}
$(document).ready(function() {
var intervalID;
$(".button").click(function(){
intervalID=setInterval(changeClass,1000);
});
$(".clear").click(function(){
clearInterval(intervalID);
});
});
Upvotes: 0
Views: 1323
Reputation: 59313
So what are you actually trying to do? If you want the start button to be ignored when the interval is already set, write your click handler like this:
$(".button").click(function() {
if(!intervalID) {
intervalID = setInterval(changeClass,1000);
}
});
If you want the start button to restart the interval then you can issue a click on the clear button every time the start button is clicked like this:
$(".button").click(function(){
// Perform a click on the clear button
$(".clear").click();
intervalID = setInterval(changeClass,1000);
});
$(".clear").click(function(){
clearInterval(intervalID);
});
Upvotes: 2