stack stack - 4 months ago 6
HTML Question

How can I run a function several times continuously?

All I'm trying to do is making a winking box. In other word I want to call a function into itself. I have this function:



$(document).ready(function(){
$("button").click(function(){
$("#div1").fadeToggle("slow");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click to fade in/out box</button><br /><br /><br />
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>





I want when user clicks on the button, that box fade in/out several time continuously as long as the time a request (ajax) takes. Currently when user clicks on the button, that box fades in/out once. Now I want to start fading in/out until a request ends. How can I do that?

Actually I'm trying to make a blinking box when a request is sending.

Answer

$(document).ready(function(){
  function toggleForever() {
    $("#div1").fadeToggle("slow", toggleForever);
  }
  
  $("button#start").click(function () {
    toggleForever();
  });
  
  $("button#stop").click(function () {
    $("#div1").stop().animate({opacity:1}, "slow");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Click to fade in/out box</button>
<button id="stop">Click to stop</button><br /><br /><br />
<div id="div1" style="width:80px;height:80px;background-color:red;"></div>

The function parameter to fadeToggle gets called when the animation is complete. On another button click, we stop the animation and fade the box in (so it's always visible when we're done, no matter where in the animation we were). In your real code, you'll do that when your AJAX call is complete.

Comments