mikelovelyuk mikelovelyuk - 1 year ago 90
Javascript Question

Expire or Time Out never ending loop after X seconds

How can I stop this process after, say, 5 seconds?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function changeBanner(){
// my change banner code
window.onload = function () { setInterval(changeBanner, 100) };

So currently I am changing the banner every 100 milliseconds. But I'd like it to stop after about 5 seconds.

I thought setTimeout might do the trick;

window.onload = function () { setTimeout(setInterval(changeBanner, 100), 5000) };

But that makes no difference.

Answer Source

I'd like it to stop after about 5 seconds.

store the return value given by setInterval and use it with clearInterval

var timer = setInterval(changeBanner, 100);
setTimeout(function() {
}, 5000);

There are also several libraries that implement function wrappers to achieve the same. For example, in underscore.js you could use _.before:

var changeBannerLimited = _.before(50, changeBanner);
var timer = setInterval(changeBannerLimited, 100);

Note that contrary to using clearInterval this will continue to call the changeBannerLimited function forever, however after being called 50 times (10 * 5 seconds) it will no longer pass the call on to changeBanner.

On a side note I chose underscore.js because I know it well and because it provides nicely formated annotated source code so you can easily understand what's really going on behind the scenes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download