KingKerosin
KingKerosin

Reputation: 3841

Delayed javascript/jQuery search using TypeScript not waiting

I'm trying to build a simple delayed search with TypeScript. I used the answer as described here @stackoverflow.

Currently, my script looks like this:

$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}]`);
}

However, there is no delay at all. Each typed letter triggers immediately the lookup-call. Is this some scope-issue with timer and waitTimeOut? Or are the 'function-definitions' in the wrong scope?

Still not sure if using the fat-arrow is correct here or not.

Upvotes: 0

Views: 922

Answers (1)

Satpal
Satpal

Reputation: 133423

As per your current implementation, you are currently invoking the function lookup(val) and passing its return value to setTimeout.

setTimeout accepts code in string format or function to execute which delayed interval.

Use

var self = this;
this.timer = setTimeout(function(){
    self.lookup(val);
}, this.waitTimeOut);

instead of

this.timer = setTimeout(this.lookup(val), this.waitTimeOut);

Upvotes: 3

Related Questions