Chaining jQuery


#1

Hi guys, I need help with chaining jQuery sequence

$('#counter')
    .fadeOut(0).delay(300).fadeIn(0).delay(300)
    .fadeOut(0).delay(300).fadeIn(0).delay(300)
    .fadeOut(0).delay(300).fadeIn(0);

This blinks an element three times and works as expected. How can I make it more DRY (as you can see it repeats the same commands), maybe using any kind of loop?


#2

Your code is readable and self-documenting as is. You could use a loop to save a couple of lines:

for (var i = 0; i < 3; i++) $("#counter").fadeOut(0).delay(300).fadeIn(0).delay(300);

Or, maybe a more reusable function that takes an element and the number of blinks as arguments for some more flexibility:

blinkElement($("#counter"), 3);

function blinkElement(element, repetitions) {
  element.fadeOut(0).delay(300).fadeIn(0).delay(300).promise().then(function() {
    if (repetitions-- > 1) blinkElement(element, repetitions);
  });
}

#3

The first one with for-loop works, thank you.

I’m still not very familiar with all that Javascript asynchronous stuff, and I need to run it sequentially (in defined order). I read somewhere that I should not use functions inside for loop. Do you think it is safe to do this so that things wouldn’t execute asynchronously?

As for promises - I’m still only planning to learn them some day :slight_smile:


#4

The for loop method will work, but you probably wouldn’t want to do it for thousands of blinks. Three is fine :slight_smile:

The function is a more robust approach, as you could copy/paste that code into any of your apps to make any element blink any number of times. It also waits until the blinking is finished before starting it again. If the promise() aspect of it seems too complicated, you could take advantage of an animation complete function in your final fadeIn() method:

blinkElement($("#counter"), 3);

function blinkElement(element, repetitions) {
  element.delay(300).fadeOut(0).delay(300).fadeIn(0, function() {
    if (repetitions-- > 1) blinkElement(element, repetitions);
  });
}

#5

Wow, javascript is infinitely expressive. Thank you a lot!