0

There is a button that its function runs couple of setTimeout functions that they all run one by one. so I want to reset the setTimeout so if I press the button again, the whole process happens again.

How can I do it?

My example code:

function add(){

setTimeout(function() {

    $(".line1").fadeIn(function(){
    $(".lineBox").animate({width: "260px"}, 
        function(){
            $(".line2").fadeIn();
            $(".text1").delay(250).fadeIn();                
        });
    });

}, 500);

setTimeout(function() {
   $(".heyyyyy").append("y");
}, 3000);

}

HTML::

<div onclick="add()"></div>

So how can I reset this setTimeout so if I run the add() function, it runs again ?

Dan
  • 577
  • 1
  • 12
  • 38
  • To cancel a timeout: `var timerId = window.setTimeout(...)` => `window.clearTimeout(timerId)`. This will only stop the timer before your animations start. I don't know the way to cancel your animations – alex Oct 19 '14 at 23:21

1 Answers1

2

To control setTimeouut assign to it a global variable:

var cid = setTimeout(...);

When you need to reset it, call clearTimout first then setTimeout

clearTimeout( cid );
cid = setTimeout( ... ); //you must reassign it to same var if you plan to reset again.

Note setTimeout runs only once. Checkout setInterval if you're looking to run some code every few seconds.

PeterKA
  • 24,158
  • 5
  • 26
  • 48