29

i'm trying to create a search where you input text into a textfield and onkeyup it will fire a function off that will send the value of the field to a page and return the results to the div container. The problem i'm having is that when someone is typing, there is a horrible lag going on. I think what's going on is that it's trying to search each letter typed in and does each request. How do i make it so that if i type into the box, wait 1/2 a second (500), if nothing is typed in, then do the ajax search,but if in that time frame another letter comes up, don't even bother with the ajax request. I've been busting my head on this and can't figure it out. All help is appreciated!

// fired off on keyup
function findMember(s) {
    if(s.length>=3)
        $('#searchResults').load('/search.asp?s='+s);
}
Sampson
  • 265,109
  • 74
  • 539
  • 565
Damien
  • 4,093
  • 9
  • 39
  • 52
  • Are you using any library for this? – Greens Apr 25 '12 at 15:17
  • 2
    It sounds like you might be trying to re-implement the wheel, vis-a-vis the jQuery Autocomplete plugin. – Tejs Apr 25 '12 at 15:17
  • 1
    That's pretty cool, and i'll keep that in mind, but for this case, the results i'm trying to load is a page with a table and other stuff on it. I'm not returning a simple array. Any other ideas? Thanks for your response! – Damien Apr 25 '12 at 15:24
  • Non-jQuery options now include Lea Verou's [Awesomplete](https://leaverou.github.io/awesomplete/) and Twitter's [typeahead.js](https://twitter.github.io/typeahead.js/). – Michael McGinnis Sep 10 '16 at 19:13

3 Answers3

55

What this will do is clear the timeout on each press, so if 1/2 second hasn't passed the func wont be executed, then set a timer for 500ms again. Thats it, no need to load a big library..

let timeoutID = null;

function findMember(str) {
  console.log('search: ' + str)
}

$('#target').keyup(function(e) {
  clearTimeout(timeoutID);
  const value = e.target.value
  timeoutID = setTimeout(() => findMember(value), 500)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="search" id="target" placeholder="Type something" />
Dominic
  • 62,658
  • 20
  • 139
  • 163
  • There is a bug : you must add a closure if you want the function not to be immediately called. – Denys Séguret Apr 25 '12 at 15:32
  • 1
    replace your last line with var $this = $(this); thread = setTimeout(function(){findMember($this.val())}, 5000); – Denys Séguret Apr 25 '12 at 15:33
  • Not sure what you mean by a "closure". Can you explain? also, i tried this code and i get no response at all. i did this: `$('#searchField').keyup(function() { ` alert('hello'); ` clearTimeout(thread); ` thread = setTimeout(findMember($(this).val()), 500); `}); i don't even get the alert – Damien Apr 25 '12 at 15:33
  • I added a commen with a fix. The problem was that findMember was immediately called, not waiting for 500ms. – Denys Séguret Apr 25 '12 at 15:34
  • 14
    I made a fiddle (with 1000ms) to demonstrate the right solution : http://jsfiddle.net/dystroy/saTm9/ – Denys Séguret Apr 25 '12 at 15:40
  • dystroy is right -thanks mate. see edited response (I originally tested it without a param too and it needed to be wrapped in an anonymous func for that to work too sorry – Dominic Apr 25 '12 at 15:43
  • That worked. Still trying to understand what happened there, but it works great. Thanks a lot! – Damien Apr 25 '12 at 15:52
6

The jquery ui autocomplete has this feature.

http://jqueryui.com/demos/autocomplete/

If you don't want to use jquery ui, then look at their source code.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • That's pretty cool, and i'll keep that in mind, but for this case, the results i'm trying to load is a page with a table and other stuff on it. I'm not returning a simple array. Any other ideas? Thanks for your response! – Damien Apr 25 '12 at 15:25
  • OK. Point taken. So infensus's answer seems to be more in line with your need. – Denys Séguret Apr 25 '12 at 15:27
3
function myFunction(inputText) {
                debugger;
                var inputText = document.myForm.textBox.value;

                var words = new Array();
                var suggestions = "Always", "azulejo", "to", "change", "an", "azo", "compound", "third"];
                if (inputText != "") {
                    for (var i = 0; i < suggestions.length; ++i) {
                        var j = -1;
                        var correct = 1;
                        while (correct == 1 && ++j < inputText.length) {
                            if (suggestions[i].toUpperCase().charAt(j) != inputText.toUpperCase().charAt(j)) correct = 0;
                        }
                        if (correct == 1) words[words.length] = suggestions[i];
                        document.getElementById("span1").innerHTML = words;

                    }
                }

                else {
                    document.getElementById("span1").innerHTML = "";

                }

<p id="demo"></p>
    <form name="myForm">
         <input type="text" name="textBox" onkeyup="myFunction()"/>
         <span id="span1"></span>
    </form>
Mayur Narula
  • 150
  • 1
  • 4