简体   繁体   中英

Run a function after user stop typing

I got a textbox that once the user stops typing, I want to update the results(what ever they type will be applied to an array of data and will filter down anything that does match what they type).

Right now I am using onBlur but this of course will only activate after they leave the textbox.

Would it be better to do onChange and put a timer that gets cancelled if they continue to type?

Or is there a better way.

Not sure if it makes a difference but I am reactjs

Vanilla javascript (no React )

 var inputElm = document.querySelector('input'); inputElm.addEventListener('input', onInput); function onInput(){ var duration = 1000; clearTimeout(inputElm._timer); inputElm._timer = setTimeout(()=>{ update(this.value); }, duration); } function update(){ console.log('Do something') } 
 <input> 

In React you would probably do it like this:

class SomeComp extends Component {
    constructor(props){
        super(props);

        this.state = {
            inputValue: ''
        }
    }

    onInput = (e) => {
        var duration = 1000;
          clearTimeout(this.inputTimer);
          this.inputTimer = setTimeout(()=>{
            this.updateInputValue( e.target.value );
        }, duration);
    }

    updateInputValue = ( value )=> {
        this.setState({
            inputValue: value
        });
    }

    render(){
        return(
            <input value={this.state.inputValue} onChange={this.onInput(evt)}/>
        )
    }
}

只需使用onkeyup事件,它将在用户释放键盘按钮时触发。

document.getElementById('inputText').onkeyup = UpdateData()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM