3

I want to display the current time in HH:mm:ss format beside this I want to display spinner single glyph that cycles through [ '↑', '↗', '→', '↘', '↓', '↙', '←', '↖' ]. (i.e. HTML glyph characters: ↑, ↗, →, ↘, ↓, ↙, ←, and ↖) The spinner should be updated every 125ms and should show ↑ when the clock ticks to each new second.

So far I am able to display the current time using the following code

function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }

    function startTime() {
      var today = new Date();
      var h = today.getHours();
      var m = today.getMinutes();
      var s = today.getSeconds();
      // add a zero in front of numbers<10
      m = checkTime(m);
      s = checkTime(s);
      document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
      t = setTimeout(function() {
        startTime()
      }, 500);
    }
    startTime();

But I am not able to display spinner which moves every 125ms

sar
  • 1,277
  • 3
  • 21
  • 48

2 Answers2

2

To clarify, the code you've currently written is managing to continuously update the time without a page refresh or is it just correctly displaying the time each time the function is run?

As for what I've written below, I'm just throwing something out here - not sure it will work as I don't see what will trigger it to run/loop continuously and act like an animation.

let index = 0
setInterval(() => {
  (index === 7) ? index = 0 : index++
}, 125)

const spinner = index => {
  const spinnerArray =  [ '↑', '↗', '→', '↘', '↓', '↙', '←', '↖' ]
  return spinnerArray[index]
}

document.getElementById('time').innerHTML = spinner(index) + " " h + ":" + m + ":" + s
Emilio
  • 1,814
  • 3
  • 9
  • 11
0

Converting from the question about sleep functions here: What is the JavaScript version of sleep()?

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    const spinnerArray =  [ '↑', '↗', '→', '↘', '↓', '↙', '←', '↖' ]
    var spinCounter = 0;
    while(true){
      console.log('Taking a break...');
      await sleep(125);
      console.log('125 ms later');
      spinCounter++;
      if(spinCounter >= spinnerArray.length) spinCounter = 0;
      document.getElementById('time').innerHTML = spinnerArray[spinCounter] 
                                                  + " " h + ":" + m + ":" + s
    }
}
Chad
  • 364
  • 2
  • 7