Question

I have a Div. I would like to hide it after 10 seconds then show it after 30 seconds then hide it again after 10sec and so on.

I have this code but it doesn't work the way I had imagined it.

setTimeout(function() { 
    $("#myDiv").hide(); 
    setTimeout(function() {     
            $("#myDiv").show(); 
    },30000);
},10000); 

Any advice?

Was it helpful?

Solution

Just loop it like

function toggleDiv() {
    setTimeout(function () {
        $("#myDiv").hide();
        setTimeout(function () {
            $("#myDiv").show();
            toggleDiv();
        }, 30000);
    }, 10000);
}
toggleDiv();

Demo: Fiddle

OTHER TIPS

Use setInterval(func, timeout) instead, it will run every timeout milliseconds and in the func toggle div between visible and hidden

Use setInterval like,

setInterval(function() { 
    $("#myDiv").hide(); 
    setTimeout(function() {     
        $("#myDiv").show(); 
    },10000);
},30000); 

Demo

You can set time accordingly like for your problem try,

setInterval(function() { 
    $("#myDiv").hide(); 
    setTimeout(function() {     
       $("#myDiv").show(); 
    },3000);
},4000); 

Updated Demo

If you don't mind the initial state being "shown", you can do this (which is what Rohan Kumar probably intended):

setInterval(function() { 
    $("#myDiv").show(); 
    setTimeout(function() {     
       $("#myDiv").hide(); 
    },10000);
},40000); 

The repeat timer is set to every 40 seconds (the total interval of 30+10) and the hide occurs after a fixed timeout of 10 seconds.

There is also a timing library that extends JQuery animation (to allow for repeats etc):

http://creativecouple.github.com/jquery-timing/

Then your code becomes something like:

$("#myDiv").repeat().wait(10000).show().wait(30000).hide();

JSFiddle: http://jsfiddle.net/TrueBlueAussie/zDV6F/1/

Which I think is pretty cool.

If you don't mind the extra calls, or don't want an extra libary, go with Arun P Johny's answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top