Lottery Animation Algorithm

Lottery Animation Algorithm

Simple algorithm, not associated with UI layer(react). In practice, using "setState" replace log.

const randomPick = arr => {
  const randomIndex =  Math.floor(Math.random() * arr.length);
  return arr[randomIndex];
}
// 多个候选者
const names = ['tick', 'jack', 'mick', 'wick'];
// 多个赢家
const winners = ['andy', 'tony', 'jane'];

// 输出间隔
const GAP = 900;

// 记录赢家次序
let winnerCounter = 0;

const status = () => {
  // 候选者循环滚动的次数
  let counter = 0;
  const selectInt = setInterval(() => {
    // 循环滚动五次时,输出赢家
    if (counter === 4) {
      console.log('winner:', winners[winnerCounter]);
      clearInterval(selectInt);
      // 赢家还未全部输出
      if (winnerCounter < winners.length - 1) {
        // 下一个赢家
        winnerCounter += 1;
        // 开启下一轮
        setTimeout(() => status(), GAP);
      } else if (winnerCounter === winners.length -1) {
        setTimeout(() => console.log('done'), GAP * 2);
      }
    } else {
      // 输出候选者
      console.log(randomPick(names));
      counter += 1;
    }
  }, GAP);
}
status()