简体   繁体   中英

h1 element text is not changing using javascript but changes in console

I'm learning web development and I'm trying to do the simplest things in javascript to learn how it works. I have this problem, the h1 text is not changing on the page but when I open the console it prints the changed value each time, here's the code (Hint, the sleep() function is from the internet and I don't know anything yet about it but it works):

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>TEST</title>
    <script>
        let counter = 0;
        function sleep(milliseconds) {
        const date = Date.now();
        let currentDate = null;
        do {
            currentDate = Date.now();
        } while (currentDate - date < milliseconds);
}
      function change(){
          while(true)
          {
          document.querySelector("#show").innerText = counter;
          counter++
          console.log(document.querySelector("#show").innerText);
          sleep(1000);
          }
      }  
    </script>
</head>

<body>
    <button onclick="change()" id="button" >COUNT</button>
    <h1 id="show">0</h1>
</body>

</html>

 <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TEST</title> <script> function change() { let counter = 0; setInterval(() => { document.querySelector("#show").innerText = counter; counter++; }, 1000); } </script> </head> <body> <button onclick="change()" id="button" >COUNT</button> <h1 id="show">0</h1> </body> </html>

try changing your change function using setInterval. you can find how to use set interval using https://www.w3schools.com/jsref/met_win_setinterval.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM