Home > other >  Javascript - document keyup event - get the whole string once the delay (timeout) is finished
Javascript - document keyup event - get the whole string once the delay (timeout) is finished

Time:11-14

I am trying to build following functionality:

User can type number on keyboard while the tab is active, and this can be a number with several digits. How can I get the whole number after the delay time between the keyup event is finished?

I have written following code, but I am getting the buffer on every keyup, and I only need to get the final result. What am I doing wrong?

The code so far:

const delay = 1000
const keystrokeDelay = delay;

let state = {
  buffer: [],
  lastKeyTime: Date.now()
};

document.addEventListener('keyup', event => {
  const key = event.key;
  const currentTime = Date.now();
  let buffer = [];

  if (currentTime - state.lastKeyTime > keystrokeDelay) {
    buffer = [key];
  } else {
    buffer = [...state.buffer, key];
  }

  state = {buffer: buffer, lastKeyTime: currentTime};
});

CodePudding user response:

I have written following code, but I am getting the buffer on every keyup, and I only need to get the final result. What am I doing wrong?

You could make use of setTimeout and clearTimeout.

const delay = 1000
const keystrokeDelay = delay;
let keyTimeout = null;

let state = {
  buffer: [],
  lastKeyTime: Date.now()
};

document.addEventListener('keyup', event => {
  window.clearTimeout(keyTimeout);

  const key = event.key;
  const currentTime = Date.now();
  let buffer = [];

  if (currentTime - state.lastKeyTime > keystrokeDelay) {
    buffer = [key];
  } else {
    buffer = [...state.buffer, key];
  }

  state = {buffer: buffer, lastKeyTime: currentTime};
  keyTimeout = window.setTimeout((wholeString) => console.log(wholeString), delay, buffer.join(''))
});

CodePudding user response:

Try this debounce foo

const input = document.getElementById('input')

function debounce(func, timeout = 1000){
  let timer;
  return (...args) => {
    clearTimeout(timer);
    timer = setTimeout(() => { func.apply(this, args); }, timeout);
  };
}

function submit(){
  console.log('Saving data', input.value);
}

input.addEventListener("keyup", debounce(submit));
<input type="text" id="input" />

  • Related