0

I'm writing a series of small functions in jQuery, with the aim of timing how long a user takes to complete a form.

The form contains inputs of various types as well as some 'continue' buttons mid form.

Here's some example bindings:

$("#application-form").on("focusin input", "input[type=text]", timerUpdate);
$("#application-form").on("click", ".stepper-action-next", timerUpdate);
$("#application-form").on("click", ".stepper-action-submit", finaliseTimer);

The aim is to measure the time taken on focus, input or click and update the overall time.

Here's a basic function (work in progress) to collect times:

function timerUpdate(e) {
    if (!start) {
        start = e.timeStamp;
        lastTriggered = e.timeStamp;
        accumulated = 0;
    }
    else {
        var elapsed = e.timeStamp - lastTriggered;

        if (elapsed < 10000) {
            accumulated += elapsed;
        }

        lastTriggered = e.timeStamp;
    }
}

The function works, although it still needs more work to ensure accuracy.

The question I have is this:

There will always be a delay between recording elapsed and updating the lastTriggered variable (The code inside the 'else').

This could potentially lead to double counting, say when a change to input is triggered, immediately followed by a focus on the next input.

In c#, we would normally but a lock around this section of code to prevent double counting but I'm unsure as to how to approach this jQuery/javascript wise.

Any help would be appreciated.

John Ohara
  • 2,821
  • 3
  • 28
  • 54
  • Possible duplicate of [What is Javascript atomic execution unit for events?](https://stackoverflow.com/questions/41059965/what-is-javascript-atomic-execution-unit-for-events) –  May 04 '18 at 12:27

1 Answers1

0

I'm not entirely sure if I understand correctly. Are you concerned that while executing timerUpdate another event is triggered also calling and therefore interrupting timerUpdate?

This can not happen. JS runs in a single thread. One event is completely executed before another can start.

Reynicke
  • 1,407
  • 1
  • 11
  • 21