0

I'm currently having difficulties creating a timer. The timer sort of works, but I'm having issues converting the milliseconds into minutes/hours/seconds.

If someone could please help me and edit/guide me through what i currently have that would be amazing!

The variable inter is set to a random number. I need some code that analyzes how big the number is and decides whether to display it as milliseconds, minutes, or hours.

// JS wait function 

setTimeout(() => {
    function toBeRepeated(){
      var inter = Math.floor(Math.random() * 90000000) + 500000; 
      testchannel.send("hi"); 
      var inter1 = (inter % 60000 / 1000).toFixed(2);
        setTimeout(toBeRepeated, inter);
            console.log("Message sent to server 1");
            console.log("Next message will be sent in " + inter1 + " seconds");

    }
    toBeRepeated();
    }, Math.floor(Math.random() * 5000) + 2000);
2
  • 1
    What exactly are you trying to do? Do you want to convert inter into seconds? Commented Dec 21, 2019 at 22:41
  • 2
    "sort of works" and "having issues" are not clear descriptions of either the problem you're experiencing, or the desired goal of the software. Please describe the requirements precisely and clearly, including examples of input and desired behaviour and output, so we know enough detail to be able to program it precisely. Thanks. Commented Dec 21, 2019 at 22:53

2 Answers 2

1

Here is a vague answer:

var inter = Math.floor(Math.random() * 90000000) + 500000; 

var hours = Math.floor(inter / 1000 / 60 / 60);
var minutes = Math.floor(inter / 1000 / 60) - hours * 60;
var seconds = Math.floor(inter / 1000) - minutes * 60 - hours * 60 * 60;
var ms = inter - seconds * 1000 - minutes * 60 * 1000 - hours * 60 * 60 * 1000;

console.log(hours + ":" + minutes + ":" + seconds + ":" + ms);

Sign up to request clarification or add additional context in comments.

Comments

0

Since the input is in miliseconds, you can use something like this so transform it to this format hh:mm:ss:ms. No .floor() needed

function formatTime(time) {
  var ms = time % 1000;
  time = (time - ms) / 1000;
  var secs = time % 60;
  time = (time - secs) / 60;
  var mins = time % 60;
  var hrs = (time - mins) / 60;

  return hrs + ':' + mins + ':' + secs + ':' + ms;
}

console.log(formatTime(50000000)) // "13:53:20:0"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.