【问题标题】:Update Javascript variable setInterval in an object created by function with更新由函数创建的对象中的 Javascript 变量 setInterval
【发布时间】:2015-08-27 13:52:09
【问题描述】:

我试图在 javascript 中创建一个停止和启动计时器函数,以便在 jQuery 中使用来记录 $('input') 的 .focus() 和 .blur() 之间的时间。

这是我目前所拥有的:

function startTimer() {

    _id = guid()
    time = 0
    timer_id = setInterval(function () {
        time++;
    }, 100);

    timer = {
        _id: _id,
        time: time,
        timer_id: timer_id,
    }

    return timer;
}

function stopTimer(timer) {
    var stop = timer.time
    clearInterval(timer.timer_id);
    return stop;
}

// usage
fieldTimes = {}


// on focus of field
$("input").on('focus', function (e) {

    element = e.target;
    var timer = startTimer();

    // on unfocus of field
    $(element).blur(function () {
        var time = stopTimer(timer);
        var field = e.target.id
        if (fieldTimes.hasOwnProperty(field)) {
            fieldTimes[field] += time;
        } else {
            fieldTimes[field] = time;
        }
    })

});

小提琴:http://jsfiddle.net/andrewblaney/Ltfvmaec/

问题是 startTimer 创建的计时器对象没有更新时间

【问题讨论】:

  • @AndrewBlaney - 注意你的变量名/声明。您在 startTimer 中使用全局 timetimer,在 focusblur 处理程序中使用本地 timertime
  • @AndrewBlaney - 每次执行 focus 处理程序时,您都会向输入添加一个新的 blur 处理程序。

标签: javascript jquery forms object timing


【解决方案1】:

当你说:

timer = {
    _id: _id,
    time: time,
    timer_id: timer_id,
}

右侧的所有值都在评估。因此,timer.time 被设置为 time 在那个时间点的整数值。它没有设置为对time 变量的引用。

一种解决方法是在间隔中简单地引用timer.time

timer_id = setInterval(function () {
    timer.time++;
}, 100);

编辑: 此外,您需要取消绑定要附加的 .blur 事件:

$(element).on("blur.timer", function () {
    // ... code here ...
    $(element).off("blur.timer");
})

Updated Fiddle

【讨论】:

  • 谢谢,问题是 timer.time++ 让它按我的预期工作,我的 jquery 似乎很好,但我不确定 blur.timer 指的是什么
  • @AndrewBlaney .timer 的一部分blur.timer 只是一个event namespace。我添加了它,以便不会删除对象上的任何其他模糊事件,只会删除带有命名空间计时器的模糊事件。
【解决方案2】:

您只是在增加计时器变量而不是时间对象。只需将您的更改为以下

timer_id = setInterval(function () {
    timer.time = time++; 
}, 100);

【讨论】:

    猜你喜欢
    • 2011-08-15
    • 2016-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    相关资源
    最近更新 更多