Javascript 如何在停止键入时触发调用
我使用的是InputChangedEvent,我们如何延迟事件如果无法将带有参数的函数传递给setTimeout,则需要创建另一个函数,在其中调用此函数:Javascript 如何在停止键入时触发调用,javascript,Javascript,我使用的是InputChangedEvent,我们如何延迟事件如果无法将带有参数的函数传递给setTimeout,则需要创建另一个函数,在其中调用此函数: <input autocomplete="off" [config]="config2" [items]="items2" (inputChangedEvent)="onInputChangedEvent($event)" (selectEvent)="onSelect($event)">`enter code here`
<input autocomplete="off" [config]="config2" [items]="items2" (inputChangedEvent)="onInputChangedEvent($event)" (selectEvent)="onSelect($event)">`enter code here`
onInputChangedEvent(val: string) {
this.changeEvent.emit(val);
this.inputChanged = val;
if (this.timer) {
clearTimeout(this.timer);
}
// trigger the search action after 400 millis
this.timer = setTimeout(this.searchFunction(val), 200);
}
通过将函数直接传递给setTimeout,JavaScript执行函数并使用返回值作为回调。因此,您的搜索功能每次都会执行。您是否在询问如何仅在400毫秒内没有键入时触发该操作 如果是这样的话,我相信通常的做法是借用火车上一个旧的安全装置来称呼一个死人 其基本思想是,每次看到击键时,都会杀死现有的计时器(如果有的话),并启动一个400毫秒的计时器
然后,如果计时器最终触发,您就知道400毫秒已经过去了,没有按键,您可以执行此操作。这称为去Bouncing。您立即调用this.searchFunctionval,将其放入匿名函数中。setTimeout=>this.searchFunctionval,200;
var _this = this;
setTimeout(function () {
_this.searchFunction(val);
}, 200);