Javascript Ninja Legal
Hoje estou aprendendo algumas coisas bacanas com o [John Resig] e logo percebi uma falha no meu Javascript que animava o link do [Feed-me]. Observe o código antigo que anima o link do [Feed-me] é feito assim:
function payAttentionForFeedMe(){
var link = document.getElementById("feedme");
setTimeout(function(){ link.style.color = 'red'}, 500);
setTimeout(function(){ link.style.color = 'green'}, 1000);
setTimeout(function(){ link.style.color = 'blue'}, 1500);
setTimeout(function(){ link.style.color = 'yellow'},2000);
setTimeout(function(){ link.style.color = 'white'}, 2500);
setTimeout(function(){ link.style.color = "orange"},3000);
}
E esta é realmente uma forma bruta de realizar a tarefa! Agora por que não fiz um for?
function payAttentionForFeedMe(){
var link = document.getElementById("feedme");
var colors = ['red','green','blue','yellow','white','orange'];
for ( var i = 0; i < colors.length; i++ ){
setTimeout(function(){ link.style.color = colors[i]}, i * 1000);
}
}
Desta forma com o for tradicional não funciona. Então hoje descobri uma forma ninja de se fazer com uma função anônima no loop.
function payAttentionForFeedMe(){
var link = document.getElementById("feedme");
var colors = ['red','green','blue','yellow','white','orange'];
for ( var i = 0; i < colors.length; i++ ) (function(i){
setTimeout(function(){
link.style.color = colors[i]
}, i * 1000)}
)(i);
}
Aprendi com [este exemplo].