How to trigger an onkeyup event that's delayed until a user pauses their typing?

后端 未结 7 764
生来不讨喜
生来不讨喜 2020-11-29 03:16

I have a textarea where people enter some text (naturally), and I want to make it so that an AJAX request is made every now and then to get some suggestions regarding what t

7条回答
  •  天涯浪人
    2020-11-29 04:06

    You could combine a keypress event handler with setTimeout so that you send an Ajax request a set amount of time after a keypress, cancelling and restarting the timer if another keypress occurs before the timer finishes. Assuming you have a textarea with id 'myTextArea' and an Ajax callback function called doAjaxStuff:

    function addTextAreaCallback(textArea, callback, delay) {
        var timer = null;
        textArea.onkeypress = function() {
            if (timer) {
                window.clearTimeout(timer);
            }
            timer = window.setTimeout( function() {
                timer = null;
                callback();
            }, delay );
        };
        textArea = null;
    }
    
    addTextAreaCallback( document.getElementById("myTextArea"), doAjaxStuff, 1000 );
    

提交回复
热议问题