Animate random numbers shuffle one by one in javascript

Viewed 47

am trying to animate the random code that is for example 20345-6423-AGFDS and what am trying to do is when generating the code to animate it digit by digit. The first digit shuffles and picks 2, then the second digit and picks 0 and on and on and on till the last.

<div id="code"></div>
<br>
<button onclick="generate()"> Generate Code </button> 

JS

function generate() {
  document.getElementById("code").innerHTML = RanCode;
}
function randomString(length, chars) {
    var result = '';
    for (var i = length; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
    return result;
}
function codeFunc(){
    return (
        randomString(5, '0123456789')
        + "-"
        + randomString(5, '0123456789')
        + "-"
        + randomString(5, 'ASDFGHJKL')
    );
}
var RanCode = codeFunc();

Example how i want them to shuffle one by one like the number inside the dice. https://javascript-tutor.net/jSample/jsp_anidice.html

1 Answers

https://jsfiddle.net/7s96d4by/

const final = codeFunc(); // Initialize it with your function
const out = document.querySelector('output')

for (let i = 0; i < final.length; i++) {
  (function initPerCharAnimation(c) {
    setTimeout(() => {
      shuffle(c)
    }, 1000 * i)
  }(final.substring(0, i + 1).split('')))
}

function shuffle(final) {
  const original = final.concat()
  let i = 0
  for (; i < 9; i++) {
    setTimeout(() => {
      // TODO use random chars instead of numbers when final.at(-1) is a char
      final[final.length - 1] = Math.random() * 10 | 0
      out.innerText = final.join('')
    }, 100 * i)
  }

  setTimeout(() => {
    out.innerText = original.join('')
  }, 100 * i)
}
Related