0

I saw the snippet below that validates an input field after every user change, but it waits for 1, 5 seconds of user inactivity before it actuallyt starts validating:

var timer;

var inputElement = document.getElementById("nameInput");
inputElement.oninput = function()
{
    delayedInputValidation(validateInput, 1500);
};

function delayedInputValidation(func, delayInMilliseconds)
{
    clearTimeout(timer);

    timer = setTimeout(func, delayInMilliseconds);
}

function validateInput()
{
    ... //stuff here
}

My questions is not about input validation, but about the timeout mechanism. I tried to generalize the delay function to make it work for arbitrary functions:

function delayedFunction(timer, func,delayInMilliseconds)
{
    clearTimeout(timer);

    timer = setTimeout(func, delayInMilliseconds);
}

The point is that you have several timers in your JavaScript, for example:

var inputTimer;
var otherTimer;
...

And if you pass along the same timer, the delay function woul clear (reset) the correct timer and then set it again using the setTimeout function.

However, this doesn't work because the timer object is passed in a reference-by-value way (discussion here), resulting in the local variable timer to be changed, but not the actual inputTimer.

How can I fix this method?

Community
  • 1
  • 1
user1884155
  • 3,616
  • 4
  • 55
  • 108

1 Answers1

2

You can use something like

var timers = {};
function delayedFunction(timer, func, delayInMilliseconds) {
    clearTimeout(timers[timer]);
    timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction('inputTimer', func1, delay1);
delayedFunction('otherTimer', func2, delay2);

Or like this:

var timers = [],
    inputTimer = 0,
    otherTimer = 1;
function delayedFunction(timer, func, delayInMilliseconds) {
    clearTimeout(timers[timer]);
    timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction(inputTimer, func1, delay1);
delayedFunction(otherTimer, func2, delay2);
Oriol
  • 274,082
  • 63
  • 437
  • 513