【问题标题】:Webpage does not updated while setting getElementById设置 getElementById 时网页未更新
【发布时间】:2021-07-25 08:07:24
【问题描述】:

我试图生成一个简单的网页会生成一个随机值。现在我可以选择一个按钮,它会从我的列表中选择一个值,但我想尝试让网页看起来像是在列表中的项目之间循环,直到它停止。下面的代码将在控制台显示中更改值,但它只会随机选择最后一个值的网页,而不是每次选择新值时更新网页。在下面的代码中,我可以使用 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 html random refresh


    【解决方案1】:

    原因是因为你使用了暂停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>

    【讨论】:

    • 这实现了我的目标,但我有一个后续问题。为了让代码运行,我必须将语法“setTimeout(()=>{Insert Code}”更改为“setTimeout(function() {Insert Code}”然后它运行没有错误。什么会导致这种语法工作有时?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-13
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多