0

So i want to make an input field, which would refresh everytime the user type something, without having to press a button or enter.

I already know about the 'oninput' event like this :

<input type='text' oninput='refresh'>

And in my script.js :

function refresh()
{
    console.log('refreshed!');
}

The problem is that this fire an event every time I just write or delete one letter. And as I will have to make SQL queries to refresh, I don't think it's very efficient to make queries for every change.

So my idea was:

  1. to find a way to fire the oninput event every 1 second, but this would feel a bit laggy;
  2. I don't know if this exists but to only fire an event when the user stop typing.

So, do you know any way I could improve my search bar?

BSeitkazin
  • 2,889
  • 25
  • 40
lairv
  • 109
  • 5
  • 1
    Check [this up](https://stackoverflow.com/a/16324620/941240) if you need something concise. Consult other answers too. A plain solution is [given there too](https://chrisboakes.com/how-a-javascript-debounce-function-works/). – Wiktor Zychla Apr 26 '20 at 19:09
  • Does this answer your question? [Run javascript function when user finishes typing instead of on key up?](https://stackoverflow.com/questions/4220126/run-javascript-function-when-user-finishes-typing-instead-of-on-key-up) – Wiktor Zychla Apr 26 '20 at 19:11

2 Answers2

0

I use debounce function from lodash for this purpose. It calls function when user'll stop typing.

MissK
  • 56
  • 3
0

using onFocus,Onblur,Onchange you can build it efficiently.

var myVar ;

In OnFocus - myVar = setInterval(MyFunction, 1000); // calls for every 1 sec.

function MyFunction() { if(dataChanged) <> and make dataChanged =false }

In Onblur - clearInterval(myVar);//To stop once user out of the textinput

To make it efficient in Onchange method set a flag(dataChanged) when ever user inputs and clear the flag in MyFunction in onFocus after the server call. to avoid unnecessary calls