How to Stop Setinterval() After Sometimes in JQuery

Introduction

Have you ever found yourself in a situation where you needed to stop the setInterval() function in jQuery after a certain period of time? If so, you’re not alone. This common problem can be a bit tricky to solve, but fear not! In this article, we’ll explore different approaches to tackle this issue and find the best solution for your needs.

Solution 1: Using setInterval()

<!DOCTYPE html>
<html>
<head>
    <title>Jquery setinterval stop after sometime</title>
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.4.2.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("button").click(function(){
  
                 $(this).attr("disabled",true);
                 $("pre").append('Stop After 1min.<br/>');
  
                 var countTime = 0;
                 var storeTimeInterval = setInterval(function(){
                    ++countTime;
                    $("pre").append(countTime*5 + 'sec.<br/>');
                    if(countTime == 12){
                        clearInterval(storeTimeInterval);
                        $("pre").append('stop');
                    }
                    
                 }, 5000);
  
            });
        });
    </script>
</head>
<body>
   
    <button>Click to Start</button>
    <pre></pre>
  

</body>
</html>

Output:-

Hopefully, it can help you…!!!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x