Run javascript function when user finishes typing instead of on key up?

The solution below solves this problem and will call X seconds after finished as the OP requested. It also no longer requires the redundant keydown function. I have also added a check so that your function call won’t happen if your input is empty.

With JQuery

//setup before functions
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms (5 seconds)

//on keyup, start the countdown
$('#myInput').keyup(function() {
    clearTimeout(typingTimer);
    if ($('#myInput').val()) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping() {
    //do something
    alert('Hello')
}

Example:

 

With Vanilla JavaScript solution:

//setup before functions
let typingTimer; //timer identifier
let doneTypingInterval = 5000; //time in ms (5 seconds)
let myInput = document.getElementById('myInput');

//on keyup, start the countdown
myInput.addEventListener('keyup', () => {
    clearTimeout(typingTimer);
    if (myInput.value) {
        typingTimer = setTimeout(doneTyping, doneTypingInterval);
    }
});

//user is "finished typing," do something
function doneTyping() {
    //do something
    alert('With Vanila Js');
}

Example:

Auto deploy projects với GitHub Actions – sử dụng ssh-action WordPress Gutenberg Block Server Side Render Add, Upload image trong Gutenberg Block Development Tạo Block Controls – Block Toolbar và Settings Sidebar trong WordPress Gutenberg Làm quen với các components thường dùng khi tạo Gutenberg Block Gutenberg Block Attributes Cách tạo Gutenberg Block trong WordPress Tổng quan về Gutenberg trong WordPress Hơn 100 hình ảnh minh họa chất lượng cao, hoàn toàn miễn phí cho products của bạn 9 ứng dụng hữu ích cho Developers

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.