Home > Software engineering >  I have tried to get random variations from the tags but it doesn’t work
I have tried to get random variations from the tags but it doesn’t work

Time:09-28

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() into setInterval
  • increase the timeout of var interval from 100 to 300 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:

https://codepen.io/tuandaodev/pen/XWgoRBe

  • Related