【问题标题】:Looping clock function using setInterval使用 setInterval 循环时钟功能
【发布时间】:2020-04-05 22:00:45
【问题描述】:

我正在尝试创建一个函数,该函数可以将一个值(用户的当前时间以秒为单位)返回到另一个变量,该变量可以在我的代码的其他地方使用。该函数返回正确的值,但我不知道如何使用setIntervalsetTimeout 使其重复。

var currenttime = clock();

function clock() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var time = (hour * 3600) + (minute * 60) + second;
    return time;
}

console.log(currenttime)

我希望变量currenttime 每秒更新一次,但将行更改为
var currenttime = setInterval(clock, 1000);
返回不正确的值。或者,我也尝试让 clock 函数重复,
但我不确定如何执行此操作,因为我使用的是 return 语句,因此函数在可以重复之前结束。

有谁知道我做错了什么?

【问题讨论】:

标签: javascript time settimeout setinterval


【解决方案1】:

每次clock 运行时分配给currentTime,但不要将return 分配给time - 因为这将在一个区间内,所以忽略返回值:

let currentTime;

function clock() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    currentTime = (hour * 3600) + (minute * 60) + second;
}

setInterval(clock, 1000);

setTimeout(() => console.log(currentTime), 2000);
setTimeout(() => console.log(currentTime), 6000);

不过,这有点奇怪——变量赋值本身并没有副作用(几乎在所有情况下)。无论使用 currentTime 变量调用clock 来获取当前秒数,都会更有意义,例如:

function clock() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    return (hour * 3600) + (minute * 60) + second;
}

document.querySelector('button').addEventListener('click', () => {
  document.querySelector('div').textContent = clock();
});
<button>Get seconds</button>
<div id="time"></div>

【讨论】:

    【解决方案2】:

    setInterval 调用的函数应该调用时钟并显示时间。

    setInterval(function(){ console.log(clock()); }, 1000);
    

    【讨论】:

      【解决方案3】:

      setInterval 仅返回一个 ID 值,该值可用于 clearInterval(ID) 以停止 setInterval 循环。

      所以,你可以这样做:

      function clock()
        {
        let [h,m,s] = (new Date().toTimeString()).match(/\d{2}/g)
        return (h*3600) + (m*60) + +s
        }
      
      var currenttime = clock();
      setInterval(() => { currenttime = clock() }, 1000);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-25
        • 1970-01-01
        相关资源
        最近更新 更多