Reputation: 673
I've inherited a bug to look at consisting of two images that "flip" and use set interval to time when this happens.
From what I believe the initial change should happen after 4 seconds, then for each image change every 12 seconds (obviously this isn't important at the minute).
At the moment the first image changes at 4 seconds and the second one at around 8.
I'm also open to any improvements that can be made to this code as well.
//SPINNING LOGO
if ($("#flipLogo").length) {
function spinLogo() {
$('#flipLogo').addClass("active");
$('#flipLogo2').addClass("active");
// console.log("yup yup");
setTimeout(function () {
$('#flipLogo').removeClass("active");
$('#flipLogo2').removeClass("active");
}, 4000);
clearInterval();
}
setInterval(function () {
spinLogo();
clearInterval();
}, 12000);
}
Upvotes: 0
Views: 107
Reputation: 1730
I believe you are looking for $.toggleClass to switch between the active states.
Additionally, as Hacketo said you are calling clearInterval
wrong - it should be called with the return value of setInterval if you want to stop the interval (I don't think you want to do this?)
Try this:
//SPINNING LOGO
function spinLogo() {
// Flip the active classes on or off
$('#flipLogo').toggleClass("active");
$('#flipLogo2').toggleClass("active");
}
if ($("#flipLogo").length) {
// after 4 seconds
setTimeout(function() {
// flip the logo
spinLogo();
// Set a timer to flip it again every 12 seconds
setInterval(spinLogo, 12000);
}, 4000);
}
Here it is in action:
//SPINNING LOGO
function spinLogo() {
// Flip the active classes on or off
$('#flipLogo').toggleClass("active");
$('#flipLogo2').toggleClass("active");
}
if ($("#flipLogo").length) {
// after 4 seconds
setTimeout(function() {
// flip the logo
spinLogo();
// Set a timer to flip it again every 12 seconds
setInterval(spinLogo, 12000);
}, 4000);
}
.flippable {
width: 100px;
height: 100px;
border: 1px solid black;
text-align: center;
display: none;
color: white;
}
.flippable.active {
display: block;
}
#flipLogo {
background: blue;
}
#flipLogo2 {
background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="flipLogo" class="flippable active">Logo 1</div>
<div id="flipLogo2" class="flippable">Logo 2</div>
(ps it is bad form to define functions inside if statements, as hoisting will move them them to a place you might not expect)
Upvotes: 2