Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  195] [ 4]  / answers: 1 / hits: 7906  / 10 Years ago, fri, march 7, 2014, 12:00:00

I'm trying to make this blinking text stop after 3 seconds (or 3-5 blinks). I've set the blink rate to about the right speed, but cannot figure out how to make it stop.



Here's the code:



$('.blink').each(function() {
var elem = $(this);
setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
} else {
elem.css('visibility', 'hidden');
}
}, 200);
});


Any suggestions?



I've compiled a jQuery fiddle here: http://jsfiddle.net/M4Fcd/173/


More From » jquery

 Answers
4

setInterval goes on indefinitely - or until stopped.



What you need to do is capture the intervalID when you create the interval and then clear the interval after you are done with it



var intervalID = setInterval(function....);

// when done
clearInterval(intervalID);


In your particular case:



$('.blink').each(function() {
var elem = $(this);
// count the blinks
var count = 1;
var intervalId = setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
// increment counter when showing to count # of blinks and stop when visible
if (count++ === 3) {
clearInterval(intervalId);
}
} else {
elem.css('visibility', 'hidden');
}
}, 200);
});


Updated fiddle http://jsfiddle.net/M4Fcd/186/


[#47080] Thursday, March 6, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lamarmaximiliand

Total Points: 388
Total Questions: 104
Total Answers: 104

Location: Oman
Member since Fri, Dec 23, 2022
1 Year ago
;