Only works on first try with listening to keystrokes on input form field using jquery listener

Here is the basic situation: I want to be able to listen to user input on a text input box, the code will use ajax to check the entry after a pause of 5 seconds, against the cached answer.
The check works just fine on the first try (after 5 seconds). But if the user blurs out to another field, then tries a second time to enter the correct answer, editing the same field, nothing happens, the ajax request is not performed. The listener seems to have disappeared or stopped working.

Here's the code on the template side:

let ajax_call = function (endpoint, request_parameters) {
   $.getJSON(endpoint, request_parameters)
            .done(response => { ...... })  //response handling
};

answerInputs.on('keydown', function(){
    answer = $(this);
    setTimeout(function(){
        var answer_seq = answer.data("sequence");
        answers[answer_seq] = answer.val();
        var request_parameters  = {'answers': JSON.stringify(answers), 'idList': JSON.stringify(idList)}
        // if scheduled_function is NOT undefined, cancel the execution of the function
        if (typeof(scheduled_function)!='undefined') {
            clearTimeout(scheduled_function);
        }
        // setTimeout returns the ID of the function to be executed
        scheduled_function = setTimeout(ajax_call, delay_by_in_ms, endpoint, request_parameters);
        }, 5000);
});
Back to Top