Stephan
Stephan

Reputation: 21

How to trigger a call when typing is stopped

<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);
}

I am using InputChangedEvent ,how can we delay the event

Upvotes: 0

Views: 50

Answers (2)

Jerodev
Jerodev

Reputation: 33216

You can't pass a function with arguments to setTimeout(), you need to create another function where in you call this function:

var _this = this;
setTimeout(function () {
    _this.searchFunction(val);
}, 200);

By passing the function directly to setTimeout, JavaScript executes the function and uses the return value as the callback. So your searchFunction is executed every time.

Upvotes: 1

David Goldfarb
David Goldfarb

Reputation: 1886

Are you asking how to trigger the action only if there has been no typing for 400msec?

If so, the usual approach is a "deadman's switch" (name borrowed from an old safety device on trains, I believe).

The basic idea is that each time you see a keystroke, you kill the existing timer (if any) and start a timer for 400msec.

Then, if the timer finally triggers, you know that 400msec have passed without a keystroke, and you can do the action.

Upvotes: 0

Related Questions