-1

Say I have a variable called seconds as below:

let seconds = 100

How would I display the this in a timer form like: 01:40 Preferebly using string interpolation like so:

`${variable}`
svoruganti
  • 523
  • 1
  • 3
  • 25
  • 1
    Your question lacks any attempt at solving this problem on your own. The idea is for you to try to get something to work and then come here with specific problems you are unable to resolve. Taking the tour and reading about [How to ask a good question](https://stackoverflow.com/help/how-to-ask) in the help center will provide all the information you need. – Randy Casburn Jan 05 '21 at 21:07

2 Answers2

0

You can do it:

let number = 100;

let minutes = Math.floor(number / 60);
let seconds = number % 60;

let timeString = `${minutes}:${seconds}`;

document.getElementById("timer").textContent = timeString;
<div id="timer"></div>
  • If possible can you make the timer have two digits like 00:00 when the value is a single digit number like 01:40 – svoruganti Jan 05 '21 at 21:22
  • 1
    @svoruganti Just do something like -> `(let minutes = Math.floor(number / 60)).toString().padStart(2, '0');` And do the same for seconds. – Keith Jan 05 '21 at 21:32
0

I would use Date() object and make a function that would run a function every second by using setInterval then after use the .innerHTML to add it to your HTML code

var current_time = document.getElementById("time");
var cur_time = new Date();

var today = new Date();

setInterval(gettime, 1000);
function gettime() {
    var hours = cur_time.getHours();
    var minutes = cur_time.getMinutes();
    var seconds = cur_time.getSeconds();
    if (minutes < 10) {
        minutes = "0" + minutes;
    }
    if (seconds < 10) {
        seconds = "0" + seconds;
    }
    var time = hours + ":" + minutes + ":" + seconds; + " ";
    
    console.log(time);
    document.getElementById("time").innerHTML = time;
}

day_of_week.innerHTML = day;

note setInterval(gettime, 1000); is used so that every second the function is being running and the current time is updated