使用setInterval()2次具有相同的功能,但参数不同

时间:2013-10-01 19:32:07

标签: javascript

让我们假设我的前端代码中有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);
}())

2 个答案:

答案 0 :(得分:0)

为什么不制作两个不同命名的函数;每个标签一个,它们都只是用适当的参数调用updateTimerLabel()。

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

答案 1 :(得分:0)

这段代码运行得很好,在参数调用中声明新对象时我搞砸了。在我把它移到外部变种后,它起作用了。