Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript – document keyup event – get the whole string once the delay (timeout) is finished

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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(''))
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading