The first example is an Immediately-Invoked Function Expression (IIFE). It is a function which immediately executes itself after creation. IIFE is a common JavaScript design pattern used by most popular libraries (jQuery, Backbone.js, Modernizr, etc) to place all library code inside of a local scope.
In ES6 this can be rewritten using the Arrow function if you want the .blinkMe
to blink just once:
(() => $('.blinkMe').fadeOut(500).fadeIn(500))();
You can chain as many fadeIn
and fadeOut
functions as you want of course. If you want it to loop infinitely I'd suggest the IIFE way.
More info about IIFE here.
About your second example. You're calling the function inside your own function (also known as recursive loop). In your case this creates an infinite loop, that's why it doesn't work. Remove the blink();
inside the function and it will work:
function blink() {
$('.blinkMe').fadeOut(500).fadeIn(500, blink);
}
blink();
Besides with javascript you can also solve this issue with CCS3 animations. CSS3 animations run in a separate thread. This is a solution without jQuery:
(function blink() {
document.getElementsByClassName('blinkMe')[0].className += ' blinkActive';
})();
// Arrow function:
//(() => document.getElementsByClassName('blinkMe')[0].className += ' blinkActive')();
.blinkMe {
width: 80px;
height: 80px;
background: deepskyblue;
}
.blinkActive {
-webkit-animation: blink 1s infinite;
animation: blink 1s infinite;
}
@-webkit-keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
@keyframes blink {
0%, 100% { opacity: 1; }
50% { opacity: 0; }
}
<div class="blinkMe"></div>
I don't know how many elements you want to blink on your page, if it's just one element you can use ids instead of classes. Keep in mind that the @keyframes
rule is not supported in IE9 or earlier versions and Opera Mini: Link.