How to stop setinterval() after sometimes in jquery?

How to stop setinterval() after sometimes in jquery?

Today now in this post i will show you How to stop setinterval() after sometimes in jquery? Sometimes you may need to stop setInterval() after a while of few time. So today here i am going to give you a simple example also with the setinterval stops after a while time.

Now in this example i will use two function as listed as bellow:

setInterval() : Call on the specified intervals time.

clearInterval() : Stop the set interval.

We can see in bellow the full example, how we can stop setinterval after five minute:

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Jquery setinterval stop after sometime</title>
    <script type="text/javascript" src="//code.jquery.com/jquery-1.4.2.min.js"></script>
</head>
<body>


    <button>Click to Start</button>
    <pre></pre>


    <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');
	        	}
	         }, 25000);
	        });
	    });
    </script>


</body>
</html>

Read Also: How to implement infinite ajax scroll pagination in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →