Numerous times I implement autocomplete in textareas which interact with servers. Instead of hitting the server on change, I decide to hit my API on each pause. I implement this by using setTimeout(), but it's tedious and looks like a hack.
How about onpause event? Won't it be cool if browsers supported this by default? I am interested in knowing your views.
Instead of setTimeout - You could use a number of alternative methods. The best one that comes to mind is promises. This will make is seem less 'hacky'.
Another method could be using a library like lodash or underscore - this will allow you to only summarise data every x-seconds. Works the same way as setTimeout() (kind of) but looks nicer and you can do more with it.
So, let me re-iterate to see if I understand correctly. Instead of listening when a user stops typing in a text box, you instead want to have an onPause event that does this automatically?
If that's so, I would suggest this isn't the best idea. Due to the fact that, for me, the event listening is enough + suggestions above. But also because onPause is already an event which is tied to audio/video http://www.w3schools.com/jsref/event_onpause.asp.
First, there shouldn't be another event since it is not, it's a behaviour of event.
I'm not sure but this was somewhere discussed and, probably, in next standard there will be a flag to delay event listeners (call them only once). Can't find any links right now and don't remember details.
Nevertheless, in such cases, as per perfomance issues, you OF COURSE should call any type/mouse events only after X ms delay, and only then start doing any heavy DOM or server calls. This is done with a simple Vanilla JS technique you already know.
To make a life a bit easier I have in BunnyJS DOM event utils - addEventOnce
You can also use CDN <script src="unpkg.com/bunnyjs@0.11.0/dist/utils-dom.min.js&qu…
P.S. I also have some useful helpers like onClickOutside
cc @maruru
Marco Alka
Software Engineer, Technical Consultant & Mentor
I am against this kind of event. It just contributes to lots of clutter we already have. The use case is too specific and the implementation of the algorithm is less than 10 lines of code.
I think, a proper solution with
setTimeout()is not tedious (as you only have to implement it once; make a library if necessary ;) ) and certainly not hacky, either.const searchBox = document.getElementById('my-search-box'); var tID = undefined; searchBox.addEventListener('keyup', ev => { if (typeof tID !== 'undefined') { clearTimeout(tID); } tID = setTimeout(displayAutocomplete, 1000); });Because of the length of the VanillaJS, I am strictly against using libraries!