1

I'm using VueJS for the front-end of my application and Laravel for the backend. Where is the best place to reduce calls to the server with a free text search?

Search input 'hello'

@keyup will make 5 server requests

1st = h
2nd = he
3rd = hel
4th = hell
5th = hello

Ideally, I would like to be able to stop server requests until the user has stopped typing, or has delayed presses in keystrokes. That way I would only be sending 1 or 2 requests to the server for each search.

Craig Ward
  • 2,425
  • 5
  • 33
  • 51
  • Possible duplicate of [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) – Troyer Aug 17 '17 at 12:34
  • You should use a throttle technique in VueJS before sending a request to the server. Its often done with a `setTimeout` function in vanilla JS, you can find a lot of resources on the web. – thefallen Aug 17 '17 at 12:34

2 Answers2

3

The way I solve this is by putting the request in a timeout, and every time another key is pressed, reset the timeout.
This makes it so that the request is only done when there hasn't been a keystroke for a certain amount of time.

function keyPressed() {

    if (window.ajaxtimeout)
        clearTimeout(window.ajaxtimeout);

    window.ajaxtimeout = setTimeout(function () {

        // Ajax request

    }, 300);

};

This example will wait for 300 milliseconds between keystrokes before sending the ajax request. I have found this to be a good value.

Jerodev
  • 32,252
  • 11
  • 87
  • 108
1

You have multiple solutions :

  • Use setTimeOut() function once the user pressed a button for example he could have 300ms to press next button before launch the server request.
  • Launch the request pressing "Enter"
Thibault Dumas
  • 1,060
  • 2
  • 10
  • 21