javascript 的故障效果

Fad*_*890 4 html javascript

我一直花时间使用 javascript 制作这种故障效果。故障效果的工作原理是循环遍历字母表( alpha or alphaCaps variable) 并在某个字母( text variable) 处停止,代码如下:

const text = 'TheThingThatDoesntEndWellWillEndWell'
const alphaCaps = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
const alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
var output = "";
var progress = 0;

function sleep(milliseconds) {
  const date = Date.now();
  let currentDate = null;
  do {
    currentDate = Date.now();
  } while (currentDate - date <
    milliseconds);
}

function glitch() {
  while (output != text) {
    var randomNums = Math.floor(Math.random() * alpha.length)
    if (alpha[randomNums] == text[progress] || alphaCaps[randomNums] == text[progress]) {
      output += text[progress];
      document.getElementById("text").innerHTML = `${output}`
      progress++;
      sleep(25);
    } else {
      document.getElementById("text").innerHTML = `${output}${alpha[randomNums]}`
      sleep(25);
    }
  }
}
Run Code Online (Sandbox Code Playgroud)
<h1 id="text"></h1>
<button onclick="glitch()">Glitch Button</button>
Run Code Online (Sandbox Code Playgroud)

问题是,当我按下按钮时,它没有显示循环过程。我尝试启用睡眠功能,但不起作用。你们都可以帮我吗...

警告:可能会使您的浏览器崩溃。

mpl*_*jan 6

你不需要睡觉。它只是挂起浏览器

  • 调用该函数,直到使用 requestAnimationFrame 完成字符串,以便按照 Jaromanda X 的建议进行更平滑的更新(由于您的 25 毫秒,我最初使用了 setTimeout)
  • 使用事件监听器(推荐使用内联事件处理程序)
  • 测试字符串的长度而不是字符串。快多了

const text = 'The Thing That Doesn\'t End Well Will End Well'
const alphaCaps = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', ' ', "'"];

const alpha = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' ', "'"];
var output = "";
var progress = 0;
const len = text.length;


function glitch() {
  if (progress >= len) {
    return;
  }  
  var randomNums = Math.floor(Math.random() * alpha.length)
  if (alpha[randomNums] == text[progress] || alphaCaps[randomNums] == text[progress]) {
    output += text[progress];
    document.getElementById("text").innerHTML = `${output}`
    progress++;
  } else {
    document.getElementById("text").innerHTML = `${output}${alpha[randomNums]}`
  }
  requestAnimationFrame(glitch);
}

// just to make it nicer
window.addEventListener("load",function() {
  document.getElementById("but").addEventListener("click",function() {
    this.hidden=true;
    glitch();
  });
})
Run Code Online (Sandbox Code Playgroud)
<h1 id="text"></h1>
<button type="button" id="but">Glitch Button</button>
Run Code Online (Sandbox Code Playgroud)