Execute two functions alternately and infinitely in javascript with delay

729 views Asked by At

I have four divs that I want to show one after the other by hiding the previous one. I use a counter with modulo operator to select the divs for displaying. So I require to execute my functions in the following way.

function show_div(counter)
***after delay***
function hide_div(counter)
***after delay***
function show_div(counter+1)
***after delay***
function hide_div(counter+1)
***after delay***
function show_div(counter+2)

How can I achieve this?

4

There are 4 answers

0
Nina Scholz On BEST ANSWER

A short solution:

show_div(0);
function show_div(counter) {
    // code here
    setTimeout(hide_div, 2000, counter);
}
function hide_div(counter) {
    // code here
    setTimeout(show_div, 2000, (counter + 1) % 4);
}
0
bcdan On

You can use setTimeout.

setTimeout(function(){show_div(counter)},delay)

But be careful. If using a while loop, you need to a separate function that creates the timeout, due to variable scope.

function timeout(func, args, delay){
  setTimeout(function(){func(args)}, delay);
}

var counter = 0
while(1){
  timeout(show_div, counter, counter*500);
  timeout(hide_div, counter, counter*500+500);
  counter++;
}

An alternative solution would be some sort of chaining function:

function show(delay, counter){
  setTimeout(function(){
    show_div(counter);
  },delay);
  setTimeout(function(){
    hide_div(counter);
    show(delay, counter+1);
  },delay*2);
}

This uses setTimeout to call other setTimeouts when it is finished. This will use less memory than the other solution.

0
Christoffer Karlsson On

You could use setInterval():

var counter = 0;
var divVisible = false;

function toggleDiv() {
    if (divVisible) {
        hide_div(counter);
        counter = (counter + 1) % 4;
        divVisible = false;
    } else {
        show_div(counter);
        divVisible = true;
    }
}

window.setInterval(toggleDiv, 1000);

First time it is run, the counter is 0 and divVisible is false, so it will show the div and flip the boolean divVisible. Next time (after 1000ms), it will hide the div, increase counter, then flip the boolean divVisible again. And so it will continue forever for your 4 divs.

0
blex On

You can do it this way:

var divs = $('.someClass'),
    numOfDivs = divs.length,
    delay = 500,
    index = -1;

showNextDiv();

function showNextDiv(){
    index = (index == numOfDivs-1) ? 0 : ++index;
    divs.eq(index).show();
    setTimeout(hideDiv, delay);
}

function hideDiv(){
    divs.eq(index).hide();
    setTimeout(showNextDiv, delay);
}
.someClass{ display: none }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<div class="someClass">1</div>
<div class="someClass">2</div>
<div class="someClass">3</div>
<div class="someClass">4</div>