I try to mimic the prototype https://codepen.io/FlorinPop17/pen/zYxvJmP?editors=0011
But my work loops strangely , it can't run all tags and when I click the start button it only flash the final one. https://codepen.io/penny289/pen/VwWGdXw?editors=0010
function randomPick(){
var times=30;
var tags=$('.tag');
function randomSelectTag(){
return tags[Math.floor(Math.random()*tags.length)];
console.log(tags)
};
console.log(tags)
function highlight(tag){
tag.classList.add('highlight');
};
function unhighlight(tag){
tag.classList.remove('highlight');
};
var result = randomSelectTag()
console.log(result)
var interval =setInterval(function(){
highlight(result);
setTimeout(function(){
unhighlight(result);
},100);
},100);
setInterval(function(){
clearInterval(interval)
setTimeout(function(){
highlight(result)
},100);
},times*100);
};
CodePudding user response:
I have fixed 2 lines:
- move
randomSelectTag()
intosetInterval
- increase the timeout of
var interval
from100
to300
to let the animation is better.
Your origin code:
var result = randomSelectTag()
console.log(result)
var interval =setInterval(function(){
highlight(result);
setTimeout(function(){
unhighlight(result);
},100);
},100);
Fixed version:
var result;
var interval =setInterval(function(){
result = randomSelectTag(); // move this line into setInterval
highlight(result);
setTimeout(function(){
unhighlight(result);
},100);
},300); // increase this time because the unhighlight timeout is 100, you should increase to let see the different.
Live demo: