1

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

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.

1
  • Wow. Thanks for the quick responses everyone. Sep 7, 2016 at 16:53

4 Answers 4

6

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() {
    clearInterval(timer)
}, 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.

1
  • 1
    I'm not a front-end developer and this is just a prototype application really. So I will probably use the clearInterval answer, thanks. I've never even heard of underscore.js but will bear it in mind if I start doing more front-end! Sep 7, 2016 at 16:57
3

You could store the return value of setInterval to a variable so that you can later cancel it:

function changeBanner(){ 
    // my change banner code
}
window.onload = function () {
    var id=setInterval(changeBanner, 100);
    window.setTimeout(function() {
        window.clearInterval(id);
    },5000);
};
3

Use clearInterval.

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

persist setInterval output in variable to be able to call clearInterval;

 window.onload = function () {

  var job= setInterval(changeBanner, 100) ;
  setTimeout(clearInterval(job), 5000)

};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.