Search code examples
javascriptjqueryinputuser-inputclient-side

Tweaking on keyup event to call API once it appears user has finished typing


I have a postcode field that has a jQuery onKeyup event - the idea is that once they have fully entered their postcode to call an Google Maps Geocoding API to get the location immediately based on this postcode.

This code works however i'd like to find a solution that will ideally not call the API multiple times but wait and see if the user has finished typing using some method of waiting for x amount of time and then calling the API.

Can anyone suggest the best way to do this?

$("#txtPostcode").keyup(function() {
    var postcode = $('#txtPostcode').val().length
    if (postcode.length >= 5 && postcode.length <= 8) {
        console.log('length is a valid UK length for a postcode');
        // some logic here to run with some way to work out if user has 'finished' typing
        callGoogleGeocodingAPI(postcode);
    }
});

Solution

  • You can use setTimeout to only make the call after typing has stopped for 250ms - this is generally enough time between keystrokes to allow the full entry. Try this:

    var timer;
    $("#txtPostcode").keyup(function() {
        clearTimeout(timer);
        timer = setTimeout(function() {
            var postcode = $('#txtPostcode').val().length
            if (postcode.length >= 5 && postcode.length <= 8) {
                console.log('length is a valid UK length for a postcode');
                // some logic here to run with some way to work out if user has 'finished' typing
                callGoogleGeocodingAPI(postcode);
            }
        }, 250);
    });
    

    You can tweak the exact timeout to better suit your needs if you feel there is too much of a delay.