如何使用While循环继续更改元素

时间:2018-10-24 02:28:37

标签: javascript while-loop

我一直试图显示一堆不断变化的字母。它们仅在我每次重新加载页面时才更改。请帮忙。

    const action = false;
    var i = 0; 
    
    function randomized() {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
      const still = document.getElementById('c1');
      const still2 = [document.getElementById('c1'),document.getElementById('c2'),document.getElementById('c3'),document.getElementById('c4'),document.getElementById('c5'),document.getElementById('c6'),document.getElementById('c7'),document.getElementById('c8'),document.getElementById('c9'),document.getElementById('c10'),document.getElementById('c11'),document.getElementById('c12')]
    
    while (action === false) {
    	i++;
    	var letter = possible.charAt(Math.floor(Math.random() * possible.length));
    	still2[i].innerHTML = letter;
    }
      /*for(var i = 0; action === false; i++){
      	var letter = possible.charAt(Math.floor(Math.random() * possible.length))
        still2[i].innerHTML = letter;
    	};*/
    }

3 个答案:

答案 0 :(得分:1)

如另一个答案中所述,while循环将锁定主线程,并且永远不会呈现任何内容。我建议使用requestAnimationFrame()函数将元素的更新排队。

以下是您可以适应特定情况的概念证明:

  • 生成随机字符的功能
  • 用户全局<span>选择器
  • 用于遍历元素,更新其内容并无限期排队下一帧的功能。
  • 出于演示目的,请在2秒钟后停止循环。请注意最后一帧动画是如何记录的,然后用于停止无限循环。

// Generate random letter
function randomLetter() {
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  return possible.charAt(Math.floor(Math.random() * possible.length));
}

// Id to stop the animation frame loop
let animationId = 0;

// Update all nodes at the same time
function updateNodes() {
  // List all nodes to update
  let nodes = document.getElementsByTagName('span');

  for (let i = 0; i < nodes.length; i++) {
    nodes[i].innerHTML = randomLetter();
  }

  // Queue the next update
  animationId = requestAnimationFrame(updateNodes);
}

// Start the animation loop
animationId = requestAnimationFrame(updateNodes);

// Stops animation after 2 seconds
setTimeout(function(){
  cancelAnimationFrame(animationId);
}, 2000);
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>

答案 1 :(得分:0)

window.onload内调用页面加载方法,然后使用localStorage

 window.onload = function() { 
        randomized(localStorage.getItem("randomString"));// Retrieve
 }

function randomized(preRandomString){
    // Store and update localStorage
    return prvRandomString + localStorage.setItem("randomString", "abc123");
}

答案 2 :(得分:0)

while循环会锁定线程,并阻止页面呈现您的每个字母。尝试使用setInterval()或类似的异步循环来释放线程并显示每个新字母:

function setRandomLetter() {
  const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  const still = document.getElementById('c1');
  const letter = possible.charAt(Math.floor(Math.random() * possible.length));

  still.innerText = letter;
}

// set a random letter every second
setInterval(setRandomLetter, 1000);
<span id="c1"></span>