设置 getElementById 时网页未更新

Webpage does not updated while setting getElementById

我正在尝试生成一个简单的网页将生成一个随机值。现在我可以 select 一个按钮,它会 select 我的列表中的一个值,但我想尝试让网页看起来像是在循环浏览列表中的项目,直到它停止。下面的代码将在控制台显示中更改值,但它只会随机显示具有最后一个值 selected 的网页,而不是每次 selected 时更新网页。在下面的代码中,我可以使用 Random1 按钮进行随机更改。 Random2 将在列表中生成不同的项目 10 次(每秒一次)但网页直到第 10 次更新才更新。

HTML代码:

<html>
<body>
<div>
    <p>Round and Round we go.  Where it will stop no one will know.  Time to play the game.</p>
    <p id="one">What is going to be?</p>
    <button onclick="random()">Random1</button>
    <button onclick="main()">Random2</button>
    <button onclick="main1()">Random3</button>
</div>
</body>
<html>

JavaScript代码: 我将以下代码插入到上面的 HTML 代码中

<script>
    var timeNow, startTime, endTime, secondsCnt, secondsDiff ;

    <!--Define the start time as the time that the script was started-->
    function start() {
        startTime = new Date();
    }
    <!--Define the end time as the time that the randomizer should complete-->
    function end() {
        var duration = 10;
        endTime = new Date(startTime.getTime() + duration*1000);
    }
    <!--Calculate the time in seconds remaining for execution-->
    function timeRemaining() {
        var timeDiff = startTime - timeNow;
        var timeElapse = endTime - timeNow;
    
        timeDiff /= 1000;
        timeElapse /= 1000;
    
        secondsDiff = Math.round(timeDiff * -1);
        secondsCnt = Math.round(timeElapse);
    }
    <!--Sleep function to pause the script for a value (in ms)-->
    function sleep(millisecondsCnt) {
        const date = Date.now();
        let currentDate = null;
        do {
            currentDate = Date.now();
        } while (currentDate - date < millisecondsCnt);
    }
    <!--Randomizer function that will select a value from a list and then update the HTML for the id-->
     function random(){
         var people = [
                    "A",
                    "B",
                    "C",
                    "D",
                    "E",
                    "F",
                    "G",
                    "H",
                    "I",
                    "J",
                    "K",
                    "L",
                    "M",
                    "N",
                    "O",
                    "P"
        ];

        <!--Define a random value and update the inner HTML (or text) for the Id "one" -->
        var ranVal = people[Math.floor(Math.random() * people.length)];
        document.getElementById("one").innerHTML = ranVal;
    
        return ranVal;
    }
    <!--Main function to call the subroutines that need to executed to select a random value-->
    function main() {
        <!-- Define the times-->
        var sleepTime = 0;
        start();
        end();
        timeNow = new Date();
    
        <!--Loop until time now reaches the endTime to terminate-->
        while (timeNow <= endTime) {
            <!--Calculate the time remaining in for the script to execute
            timeRemaining();
        
            <!--Wait for 1 second before continuing to execute-->
            sleep(1000);
        
            <!--Call the function that will calculate the random value-->
            var newVal = random();
            console.log(document.getElementById("one").innerHTML);

            <!--I tried to write to the tag during the main instead of the random function, but I got the same results-->
            <!--document.getElementById("one").innerHTML = newVal;-->

            <!--Reset the time now variable-->
            timeNow = new Date();
        }
    }
</script>

下面是我为 Random3 按钮尝试的第二个函数,但我得到了相同的结果。对于第三种方法,我尝试使用 setInterval 和 clearInterval 命令。

<!--Different attempt to achieve the goal of changing the value to multiple random values. -->
function main1() {
    var sleepTime = 0;
    start();
    end();
    timeNow = new Date
    var myInterval = setInterval(random(),1000);
    while (timeNow <= endTime) {
        timeRemaining();
        sleepTime = (1 * Math.pow(Math.E,(0.7*secondsDiff)));
        <!--Just used this to slow down the output for now-->
           sleep(1000);
        
        var newVal = random();
        console.log(document.getElementById("one").innerHTML);
        <!--document.getElementById("one").innerHTML = newVal;-->
        
        timeNow = new Date();
    }
    clearInterval(myInterval);
}

现在我只想能够循环浏览列表中的项目 10 秒(每秒更改一次)但后来我打算让它看起来有点像循环浏览值一样在一个轮子上旋转。代码似乎在执行预期的功能,但网页的更新方式与值不同。

原因是因为你使用了暂停javascript的while循环,一切都暂停了,浏览器无法渲染网页,按钮无法点击,整个网站基本上停止了。它只在完成之前更改的原因是它只是不断 运行 while 循环,浏览器只有在完成 运行 之前才有时间渲染。使用 while 循环并不是执行此操作的好方法,我建议像这样使用 setTimeout:

setTimeout(()=>{
    //code here
},1000) // 1000 is in milliseconds

设置超时后,它是异步的,不会阻止正在发生的所有其他事情并减慢一切。

还有一个就是设置间隔,每隔一定的时间重复一次代码。

这就是您的代码所需的全部内容:

var counter = 0
function random(){
     var people = [
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "I",
                "J",
                "K",
                "L",
                "M",
                "N",
                "O",
                "P"
    ];

    var ranVal = people[Math.floor(Math.random() * people.length)];
    document.getElementById("one").innerHTML = ranVal;

    return ranVal;
}
function main() {
    if(counter < 10){ // check if it has looped 10 ten times already
         setTimeout(()=>{
            var newVal = random();
            console.log(document.getElementById("one").innerHTML);
            counter ++ 

            main() //calls the function again
        },1000)
    }else{
        counter = 0 //if it has looped 10 times reset the counter and stop
    }
}
<html>
<body>
<div>
    <p>Round and Round we go.  Where it will stop no one will know.  Time to play the game.</p>
    <p id="one">What is going to be?</p>
    <button onclick="random()">Random1</button>
    <button onclick="main()">Random2</button>
    <button onclick="main1()">Random3</button>
</div>
</body>
<html>