简体   繁体   English

如何在 JavaScript 中制作计时器?

[英]How to make a timer in JavaScript?

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.变量inter被设置为一个随机数。 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);

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);

Since the input is in miliseconds, you can use something like this so transform it to this format hh:mm:ss:ms.由于输入以毫秒为单位,因此您可以使用类似的内容,将其转换为 hh:mm:ss:ms 格式。 No .floor() needed不需要 .floor()

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM