Mikail G.
Mikail G.

Reputation: 478

Make ajax search function less consuming buy delaying it for 3 seconds while user is typing

My current function is lisenning for events - propertychange change keyup input paste and makes an ajax request. However ajax sends request on every letter and I believe its not an efficient way? or is it?

So, my goal is to have user type the input and only after 3 seconds ajax would be executed. Using setTimeout doesn't do the job.

$(document).on('propertychange change keyup input paste', '#IDaccountSearchQueryInput', function (event) {
    var query = $('#IDaccountSearchQueryInput').val();
    setTimeout(function () {
        console.log(query);
    }, 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="IDaccountSearchQueryInput">

This snippet gives me:

h
he
hel
hell
hello
hello

So, it executes on each keypress, but I need execution of value in input every X seconds, not every letter.

Upvotes: 2

Views: 69

Answers (1)

Ben Fortune
Ben Fortune

Reputation: 32127

You can do this by storing the setTimeout id in a variable, then clearing it when you start typing.

var timer;
$(document).on('propertychange change keyup input paste', '#IDaccountSearchQueryInput', function() {
    if(timer) clearTimeout(timer);
    var query = this.value;
    if(!query.length) return false;
    timer = setTimeout(function() {
        $('#preview').text(query);
    }, 3000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="IDaccountSearchQueryInput" />
<div id="preview"></div>

Upvotes: 7

Related Questions