Search code examples
javascriptjqueryfunctioncleartimeout

Clear timeout of a functions inside global function


I have set a function that loads on document ready with name myFunction. There are 5 functions inside it with different timeouts. I want to clearTimeout of 3rd and 4th functions on clicking a button inside my html code with id #btn . Here is my code

<doctype! HTML>
<html>
<head>
<title>
My Page
</title>
<script src="jquery-3.2.1.js">
<script src="myScript.js">
<script type="text/javascript">
$(document).ready(myFunction);
</script>
</head>
<body>
<button id="btn">
</body>
</html>

myScript.js is below

function myFunction(){
setTimeout(function function1(){
 // do stuffs
}, 5000);
setTimeout(function function2(){
 // do stuffs
}, 10000);
setTimeout(function function3(){
 // do stuffs
}, 15000);
setTimeout(function function4(){
 // do stuffs
}, 20000);
setTimeout(function function5(){
 // do stuffs
}, 25000);
}

Solution

  • To clear a timeout, you must assign it to a variable which holds the reference. Here is an example:

    var t1,t2,t3,t4,t5;
    
    function myFunction(){
        t1 = setTimeout(function function1(){
         // do stuffs
        }, 5000);
        t2 = setTimeout(function function2(){
         // do stuffs
        }, 10000);
        t3 = setTimeout(function function3(){
         // do stuffs
        }, 15000);
        t4 = setTimeout(function function4(){
         // do stuffs
        }, 20000);
        t5 = setTimeout(function function5(){
         // do stuffs
        }, 25000);
    }
    
    function myClearFunction(){
        clearTimeout(t3);
        clearTimeout(t4);
    }
    

    Call myClearFunction() from your button to clear the third and forth timers.