我正在尝试使用 TypeScript
构建一个简单的延迟搜索。我使用了此处描述的答案@stackoverflow .
目前,我的脚本如下所示:
$searchInput: JQuery;
timer: number;
waitTimeOut = 3000;
init() : void{
this.$searchInput.on("input propertychange paste", this.handleSearchInputChange);
}
handleSearchInputChange = (evt: Event): void => {
var $theInput = $(evt.currentTarget);
clearTimeout(this.timer);
var val = $theInput.val();
this.timer = setTimeout(this.lookup(val), this.waitTimeOut);
}
lookup = (searchTerm: string): void => {
console.log(`I should start a search with [${searchTerm}]`);
}
但是,根本没有延迟。每个键入的字母都会立即触发查找
调用。
这是 timer
和 waitTimeOut
的范围问题吗?或者“函数定义”的范围错误?
仍然不确定这里使用 fat-arrow
是否正确。
最佳答案
根据您当前的实现,您当前正在调用函数 lookup(val)
并将其返回值传递给 setTimeout
.
setTimeout
接受字符串格式的代码或函数来执行延迟间隔。
使用
var self = this;
this.timer = setTimeout(function(){
self.lookup(val);
}, this.waitTimeOut);
而不是
this.timer = setTimeout(this.lookup(val), this.waitTimeOut);
关于javascript - 使用 TypeScript 的延迟 javascript/jQuery 搜索不等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36789374/