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

前端 未结 29 2483
我寻月下人不归
我寻月下人不归 2020-11-22 04:03

I want to trigger an ajax request when the user has finished typing in a text box. I don\'t want it to run the function on every time the user types a letter because that wo

29条回答
  •  执笔经年
    2020-11-22 04:32

    I don't think keyDown event is necessary in this case (please tell me why if I'm wrong). In my (non-jquery) script similar solution looks like that:

    var _timer, _timeOut = 2000; 
    
    
    
    function _onKeyUp(e) {
        clearTimeout(_timer);
        if (e.keyCode == 13) {      // close on ENTER key
            _onCloseClick();
        } else {                    // send xhr requests
            _timer = window.setTimeout(function() {
                _onInputChange();
            }, _timeOut)
        }
    
    }
    

    It's my first reply on Stack Overflow, so I hope this helps someone, someday:)

提交回复
热议问题