0

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>
Ali
  • 30
  • 6
  • Please do not ever use any such `sleep` implementations in JavaScript, they are really _bad_. – CBroe Dec 07 '20 at 13:51
  • @CBroe I can see and I'm very new to js I know nothing actually. thanks for the tip – Ali Dec 07 '20 at 13:55
  • Some more details on that (and a `sleep` implementation that is actually supposed to work without the disadvantages of older approaches), can be found under https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – CBroe Dec 07 '20 at 13:58

1 Answers1

0

<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