skip to Main Content

I am making a website in which it has a auto timer, which adds numbers every second (in js). I added for the timer the id ‘timer’. I also want it to auto-scroll but I have not worked on that yet.

I tried to do this:

var timer = document.getElementById('timer')
var time = 1
while (true) do{
    await delay(1000)
    timer.innerHTML = timer.innerHTML + time
    time = time + 1

I also still need to add auto-scroll too

2

Answers


  1. Use the scroll function to scroll to {x, y}. Get the width from the scrollWidth property.

        var timer = document.getElementById('timer')
        var time = 1
        setInterval(() => {
            timer.innerHTML += time;
            time++;
            timer.scroll(timer.scrollWidth,0);
        }, 100);
    #timer {
        width: 200px;
        overflow-x: scroll;      
    }
    <div id="timer"></div>
    Login or Signup to reply.
  2. Your current approach is not valid JS code, you should use setInterval to acheive the repeated action
    You can follow this function:

        function startTimer() {
        var timer = document.getElementById('timer');
        var time = 1;
    
        setInterval(function() {
            timer.innerHTML = timer.innerHTML + time + " ";
            time = time + 1;
            timer.scrollTop = timer.scrollHeight; // Auto-scroll
        }, 1000);
    }
    
    startTimer();
    

    Here is a sample implementation in html

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Timer</title>
      <style>
        #timer {
          height: 200px;
          overflow-y: auto;
          border: 1px solid black;
          padding: 10px;
        }
      </style>
    </head>
    
    <body>
      <div id="timer"></div>
    
      <script>
        function startTimer() {
          var timer = document.getElementById('timer');
          var time = 1;
    
          setInterval(function() {
            timer.innerHTML = timer.innerHTML + time + " ";
            time = time + 1;
            timer.scrollTop = timer.scrollHeight; // Auto-scroll
          }, 1000);
        }
    
        startTimer();
      </script>
    </body>
    
    </html>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search