The first example is an Immediately Invoked Function ( IIFE ) expression . This is a function that immediately does its job after being created. IIFE is a common JavaScript design pattern used by most popular libraries (jQuery, Backbone.js, Modernizr, etc.) to put all the library code inside a local area.
In ES6, this can be rewritten using the Arrow function if you want .blinkMe to .blinkMe only once
(() => $('.blinkMe').fadeOut(500).fadeIn(500))();
You can combine as many fadeIn and fadeOut functions as you want. If you want it to loop infinitely, I would suggest an IIFE path.
Read more about IIFE here .
About your second example. You call a function inside your own function (also called a recursive loop). In your case, this creates an infinite loop, so it does not work. Remove blink(); inside the function and it will work:
function blink() { $('.blinkMe').fadeOut(500).fadeIn(500, blink); } blink();
In addition, with javascript, you can also solve this problem with CCS3 animation. CSS3 animations run in a separate thread. This is a solution without jQuery:
(function blink() { 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 do not know how many elements you want to blink on your page, if only one element you can use ids instead of classes. Keep in mind that the @keyframes rule @keyframes not supported in IE9 or earlier, and Opera Mini: Link .
source share