0

假设我的前端代码中有 2 个标签,每个标签代表一个计时器,并且它们必须每秒更新一次。为此,我创建了一个 javascript 函数来完成这项工作,它接收实际的 DateTime 和标签 ID。

现在,我想将函数注册到 setInterval 方法两次,每次都有自己的参数。知道为什么以下代码不起作用吗?

(function () {
    function updateTimerLabel(label, currentDateTime) {
        currentDateTime.setSeconds(currentDateTime.getSeconds() + 1);
        label.text(currentDateTime.getHours().toString() + ":" + currentDateTime.getMinutes().toString() + ":" + currentDateTime.getSeconds().toString());
    }
    ;
    setInterval(function () { updateTimerLabel(label1, dateTime1); }, 1000);
    setInterval(function () { updateTimerLabel(label2, dateTime2); }, 1000);
}())
4

2 回答 2

0

这段代码工作得很好,在参数调用中声明新对象时我搞砸了。在我将它移到外部变量之后,它就起作用了。

于 2013-10-02T17:51:55.407 回答
0

为什么不做两个不同命名的函数呢?每个标签一个,它们都只需使用适当的参数调用 updateTimerLabel()。

您正在通过第二次调用 setInterval 有效地重置第一个计时器,因为它们具有相同的函数名称参数。

于 2013-10-01T19:45:27.000 回答