This is what i am trying to accomplish: when the last slide is reached fadeOut last slide and then fadeIn first slide, and then clearInterval (everything works with this part). Now my problem is that i want to setInterval again if it doesn't exists but I don't know how to make it happen:(
I have tried to solve this with if statment but then my script doesn't work at all!
So how can I RESTART my interval again? THANK YOU!!
Without if statement like this it's working fine:
if(!intervalID){
intervalID = setInterval(animate,5000);
}
This is what I have so far:
$(document).ready(function() {
/*check if intervalID don't exists messes UP!!*/
if (!intervalID) {
intervalID = setInterval(animate, 5000);
}
//Hide everything except first slide and controls
$('.slidewrap div:not(.slidewrap div:first,.slidewrap .slide_controls)').hide();
var animate = function() {
/*if .pagination_active is last removeClass and addClass to .pagination_active
first li tag*/
if ($('.pagination_active').is($('.slide_controls ul li:last'))) {
$('.pagination_active').removeClass('pagination_active');
$('.slide_controls ul li:first').addClass('pagination_active');
} else {
$('.pagination_active').removeClass('pagination_active').next().addClass('pagination_active');
}
/*if div.active is last fadeOut and add .active class
to the first div and fadeIn FIRST div then CLEAR INTERVAL and set intervalID to zero */
if ($('.active').is($('.slidewrap div:last'))) {
$('.active').fadeOut(1000).removeClass('active');
$('.slidewrap div:first').addClass('active').fadeIn(1000, function() {
clearInterval(intervalID);
intervalID = 0;
});
}
//OR .active fadeOut and next div fadeIn
else {
$('.active').fadeOut(1000).next().fadeIn(1000, function() {
$('.slidewrap div.active').removeClass('active').next('div').addClass('active');
});
}
}
var intervalID;
intervalID = setInterval(animate, 3000);
});
After clear an interval you need to start it again with setInterval()
.
It would be better to make function for your setInterval()
var intervalID = null;
function intervalManager(flag, animate, time) {
if(flag)
intervalID = setInterval(animate, time);
else
clearInterval(intervalID);
}
Here flag
is a boolean
variable with value true/ false
. true
will execute setInterval()
and false
will clearInterval()
;
Now you can use above function as you need.
For example:
intervalManager(true, animate, 300); // for setInterval
intervalManager(false); // for clearInterval
Just Example
var myVar
function myTimer() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = t;
}
function myStopFunction() {
clearInterval(myVar);
}
function myStartFunction() {
myVar = setInterval(myTimer, 1000);
}
myStartFunction();
<p id="demo"></p>
<button onclick="myStopFunction()">Stop time</button>
<button onclick="myStartFunction()">Start time</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With