elreeda
elreeda

Reputation: 4597

Show and hide a div every 1s

Hi i want to show a div for 1s and hide 1s and loop this code :

<div>Flashing</div>

    <script>
        $(document).ready(function(){
        hide();

        function show(){
          setTimeout(function(){
            $('div').show();
          }, 2000);
          hide();
        }

        function hide(){
          setTimeout(function(){
            $('div').hide();
          }, 2000);
          show();
        }
      });
    </script>

But the browser give me a error: the error:

Uncaught RangeError: Maximum call stack size exceeded

Upvotes: 0

Views: 79

Answers (5)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You show and hide function call is not in the Async part of your function, resulting into an infinite loop. Put your call inside the timer event :

  $(document).ready(function(){
    hide();

    function show(){
      setTimeout(function(){
        $('div').show();
        hide();
      }, 2000);
    }

    function hide(){
      setTimeout(function(){
        $('div').hide();
        show();
      }, 2000);
    }
  });

Upvotes: 1

Varun
Varun

Reputation: 1946

It would be better if you use the .toggle() method of jquery/

setInterval(function(){
        $('div').toggle();
      }, 1000);

Upvotes: 3

Juho
Juho

Reputation: 427

You should put $('div').show(); outside timeout and hide(); inside and vice versa for hide function.

In it's current form the script goes into infinite recursion: the hide immediately calls show, and show immediately calls hide, until the script runs out of stack space (~memory).

See https://en.wikipedia.org/wiki/Call_stack for more information.

Upvotes: 0

jdu
jdu

Reputation: 571

$(document).ready(function(){

var t = setInterval("$('div').toggle()", 1000);

});

Upvotes: 0

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28455

Try this

 $(document).ready(function(){

    function toggleDiv() {
        $('div').toggle();
        setTimeout(function(){toggleDiv();}, 1000);
    }

    toggleDiv();

});

Upvotes: 0

Related Questions