Reputation: 13
I have created a function which toggles the classes of elements in my HTML with a set time out function. I would like to repeat this function at the end, quite like a loop. I have tried calling the function at the end of this function inside itself, this does not work. What is the proper way to do this?
jQuery( document ).ready(function() {
var rectanglePre = jQuery('.rectangle-pre');
function myRemovePre(index){
jQuery(rectanglePre[index]).toggleClass('rectangle-transparent');
}
function transparent(index){
jQuery(rectanglePre[index]).toggleClass('rectangle-transparent');
}
function preloader(index){
setTimeout(function(){ myRemovePre(1) }, 100);
setTimeout(function(){ myRemovePre(0) }, 200);
setTimeout(function(){ transparent(0) }, 300);
setTimeout(function(){ transparent(1) }, 400);
}
preloader(0);
});
Upvotes: 1
Views: 136
Reputation: 780852
It should call itself after the last action in the setTimeout()
.
function preloader(index){
setTimeout(function(){ myRemovePre(1) }, 100);
setTimeout(function(){ myRemovePre(0) }, 200);
setTimeout(function(){ transparent(0) }, 300);
setTimeout(function(){ transparent(1); preloader(index) }, 400);
}
jQuery(document).ready(function() {
var rectanglePre = jQuery('.rectangle-pre');
function myRemovePre(index) {
jQuery(rectanglePre[index]).toggleClass('rectangle-transparent');
}
function transparent(index) {
jQuery(rectanglePre[index]).toggleClass('rectangle-transparent');
}
function preloader(index) {
setTimeout(function() {
myRemovePre(1)
}, 100);
setTimeout(function() {
myRemovePre(0)
}, 200);
setTimeout(function() {
transparent(0)
}, 300);
setTimeout(function() {
transparent(1);
preloader(index);
}, 400);
}
preloader(0);
});
.rectangle-pre {
height: 50px;
width: 50px;
background-color: yellow;
}
.rectangle-pre.rectangle-transparent {
background-color: white;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="rectangle-pre"></div>
<p>
<div class="rectangle-pre"></div>
Upvotes: 1