ItsDjoki
ItsDjoki

Reputation: 97

Future.delayed and Timer are executing all of the delayed callbacks

So this is the deal. I am using Places autocomplete API in my app, so in Textfield's onChanged function I am making request to it for each letter typed. This costs a lot and I tried using Future.delayed to delay this call. So I wrapped the whole function in Future.delayed and gave it a 2 seconds delay. Now it waits 2 seconds but after 2 seconds it executes all the delayed call.

Example:

typing: 'New York' (within 2 seconds) result: waits 2 seconds and executes following: Ne, New, New , New Y, New Yo, New Yor, New York..

So basically it delays it but then executes it all at once. How do I solve this?

PS: I did try to wrap onchanged function itself as well the function responsible for api calls.

Upvotes: 0

Views: 381

Answers (1)

wxker
wxker

Reputation: 1896

The onChanged function will trigger on every change, meaning for every letter that is typed. Future.delayed does not change this behavior and instead delays every call of the function.

What you are looking for is debounce or throttle functions. Consider using a library such as this that provides them.

Upvotes: 1

Related Questions