JSFiddle - React, Tailwind, and code Playground

by john_s

HTML

<input type="text" id="input_username" />
<span id="username_info"></span>

JavaScript

$('#input_username').on('input', function() {
    var $input = $(this),
        value = $input.val();

    // Abort any previous timeout or ajax call.
    if ($input.data('jqxhr')) {
        $input.data('jqxhr').abort();
        $input.removeData('jqxhr');
    }
    if ($input.data('timeoutId')) {
        clearTimeout($input.data('timeoutId'));
        $input.removeData('timeoutId');
    }
        
    // Clear the validation message.
    $('#username_info').empty();
        
    // Don't bother making the ajax call if the input is empty.
    if (value) {
        // Delay the ajax call for a quarter second.
        var timeoutId = setTimeout(function() {
            var jqxhr = $.post('/echo/html/', {
                html: $input.val(),
                delay: 0.5
            }, function(responseText) {
                // For testing, only "abc" will be available.
                if (responseText == 'abc') {
                    $('#username_info').html('user name available');
                } else {
                    $('#username_info').html('user name not available');
                }
            });
            $input.data('jqxhr', jqxhr);
        }, 250);
        $input.data('timeoutId', timeoutId);
    }
});