Jquery random words without repeating

后端 未结 1 1631
情深已故
情深已故 2021-01-29 06:48

I need to display random words in div without repeating the word. The random words will append a div every random seconds (3-5 seconds). If all value in array displayed in div,

1条回答
  •  逝去的感伤
    2021-01-29 07:25

    Here's a working solution:

    $(document).ready(function() {
      var words = ['a', 'b', 'c', 'd'];
    
      var getRandom = function() {
        var idx = Math.floor(Math.random() * words.length);
        // grabs word and removes it from the array
        return words.splice(idx, 1)[0];
      };
    
      var appendIfMore = function() {
        var word = getRandom();
        if (!word) return; // all done
    
        $('
    ') .text(word) .appendTo('#container'); var delay = Math.round(Math.random() * (3000 - 500)) + 500; setTimeout(appendIfMore, delay); }; // start appending stuff appendIfMore(); });

    JSBIN

    0 讨论(0)
提交回复
热议问题