Emo
Emo

Reputation: 620

clearInterval stopping setInterval working purely time based

I'm newbie in JS/jQuery, and got quite confused about the usage of stopping a setInterval function from running in x ms (or after running X times), which apparently happens with clearInterval. I know this question was asked similarly before, but couldn't help me.

As you see, it starts with 1000ms delay, and then repeat for 9000ms (or after running 3 times if better??), and then it needs to stop. What's the most ideal way of doing this? I couldn't properly use the clearInterval function. Thanks for the answers!

var elem = $('.someclass');

setTimeout(function() {
    setInterval(function() {
        elem.fadeOut(1500);
        elem.fadeIn(1500);
    },3000);
},1000);

Upvotes: 1

Views: 478

Answers (4)

Guffa
Guffa

Reputation: 700312

To stop the interval you need to keep the handle that setInterval returns:

setTimeout(function() {
    var cnt = 0;
    var handle = setInterval(function() {
        elem.fadeOut(1500);
        elem.fadeIn(1500);
        if (++cnt == 3) clearInterval(handle);
    },3000);
},1000);

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93561

Given what you are trying to do is quite static, why not simply add delays and forget all the timers.:

var elem = $('.someclass');
elemt.delay(1000).fadeOut(1500).fadeIn(1500).delay(3000).fadeOut(1500).fadeIn(1500).delay(3000).fadeOut(1500).fadeIn(1500).delay(3000);

Or run the above in a small loop if you want to reduce the code size:

elemt.delay(1000);
for (var i = 0; i < 3; i++){
   elemt.fadeOut(1500).fadeIn(1500).delay(3000);
}

Upvotes: 1

Jivings
Jivings

Reputation: 23250

You just need to clear the interval after three times:

setTimeout(function() {
    var times = 0;
    var interval = setInterval(function() {
        elem.fadeOut(1500);
        elem.fadeIn(1500);
        if (++times > 3) clearInterval(interval);
    },3000);
},1000);

Upvotes: 0

James Thorpe
James Thorpe

Reputation: 32202

Create a counter, and keep a reference to your interval. When the counter hits 3, clear the interval:

var elem = $('.someclass');

setTimeout(function() {
    var counter = 0;
    var i = setInterval(function() {
        elem.fadeOut(1500);
        elem.fadeIn(1500);
        counter++;
        if (counter == 3)
            clearInterval(i);
    },3000);
},1000);

Upvotes: 1

Related Questions