How to reset a setTimeout function in a button so it can run again

1.1k Views Asked by At

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 ?

1

There are 1 best solutions below

0
PeterKA On

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.