Kyle
Kyle

Reputation: 1183

Determine amount of time after user presses key (onKeyUp)

I'm trying to determine the amount of time (seconds) after a user presses a key. This is for the value of an input box.

I'd like to pragmatically call an updateData function as the value of the textbox changes, but only after a specific duration of onKeyUp.

I'm currently checking the value.length and calling the updateData function if more than 3 characters are entered... is there an easy way to determine the amount of time after onKeyUp?

<input id="location" onkeyup="delayUpdate()">

<script>

var input = document.getElementById("location").value;

function delayUpdate() {
    if (input.length > 2) {
        updateData();
    }
}

function updateData() {
    console.log(input);
}

</script>

Upvotes: 1

Views: 83

Answers (2)

Shomz
Shomz

Reputation: 37701

You can keep track of time when the key is pressed and compare it to the release time:

var timer, interval;
var threshold = 2000; // 2 secs in this example

function delayUpdate() {
  console.log('key held for: ' + (new Date() - timer) + 'ms');
  if (timer && new Date() - timer > threshold) {
    updateData();
  }
  timer = false;
}

function updateData() {
  alert(document.getElementById("location").value);
}

function startTimer() {
  if (!timer)
    timer = new Date();
}
<input id="location" onkeyup="delayUpdate()" onkeydown="startTimer()">

Upvotes: 1

adeneo
adeneo

Reputation: 318182

Sounds like you're looking for a debounce effect to avoid sending the data on every keystroke.

Something like this would do that

var input = document.getElementById("location");
var timer = null;

input.addEventListener('keyup', delayUpdate, false);

function delayUpdate() {
    var self = this;

    clearTimeout(timer);

    timer = setTimeout(function() {
        if (self.value.length > 2) {
            updateData(self);
        }
    }, 1000); // a second

}

function updateData(input) {
    console.log(input.value);
}

FIDDLE

Upvotes: 2

Related Questions