I have text input like this and it will perform a search on every key input by user. Since the search function takes bit of time to execute user input is stuck until it finishes the execution.
<input type="text" id="suggestion" onkeyup="search();"/>
Can we let this search function execute and let the user type in the text field. Something like letting the search run in background.
ps. I don't want to use a delaying function to wait until user finishes and call search()
-
2Try Debouncing: davidwalsh.name/javascript-debounce-functionTim Ackroyd– Tim Ackroyd2015年11月05日 22:27:09 +00:00Commented Nov 5, 2015 at 22:27
-
Where are you outputting your result?smcjones– smcjones2015年11月05日 22:45:48 +00:00Commented Nov 5, 2015 at 22:45
-
I'm searching about 3000 rows to find some text details. And if there's anything matching to my search criteria a simple UI change will be done. That's the idea.Asiri Liyana Arachchi– Asiri Liyana Arachchi2015年11月06日 18:50:09 +00:00Commented Nov 6, 2015 at 18:50
-
@Tim Ackroyd that answer is not what I'm looking for. That's what I meant by ps. guess. :) Btw thanks.Asiri Liyana Arachchi– Asiri Liyana Arachchi2015年11月06日 18:52:15 +00:00Commented Nov 6, 2015 at 18:52
2 Answers 2
JavaScript is running on a single thread - therefore, when the search function is running, it also blocks the UI from rendering and responding to you. You should avoid as much as possible doing operations on the browser that last more than 16ms, you can read more about the reasons here.
Anyway, currently there are 2 primary solutions for this:
- Move it to the server-side. What's the search logic that you run in JavaScript? should it really run on the client-side and not on the server-side?
- Execute it on another thread. Are you familiar with WebWorkers? It's a more advanced topic, but generally it allow you to execute code on another thread. It's quite new and not fully supported yet in today's browsers, but you should at least be familiar with it.
Good luck.
Comments
Maybe instead of letting it run every time set a global switch using
window.somevar = true;
Then check if that variable is set before searching again. Once the initial search is complete then show your results and unset the global variable
delete window.somevar;
That way the function "runs" each keystroke, but doesn't lock up the input.