Search code examples
javascriptjqueryhtmlfrontendweb-frontend

Execute two functions alternately and infinitely in javascript with delay


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?


Solution

  • 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);
    }