Search code examples
javascriptjqueryformsobjecttiming

Update Javascript variable setInterval in an object created by function with


Im trying to create a stop and start timer function in javascript for use in jQuery to record the time between a .focus() and .blur() of a $('input').

This is what I have so far:

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

});

Fiddle: http://jsfiddle.net/andrewblaney/Ltfvmaec/

The problem is that time is not being updated on the timer object created by startTimer


Solution

  • When you say:

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

    All the values on the right-hand side are being evaluated. Thus, timer.time is set to the integer value that time was at that point in time. It is not set as a reference to the time variable.

    One fix is to simply reference timer.time in the interval:

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

    Edit: Also, you need to unbind the .blur event you're attaching:

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

    Updated Fiddle