I have a function that is being called when the user is typing in a search box. I want to wait for the user to finish typing before I actually execute the function. I know how to easily accomplish this in JavaScript with timeouts, but how would I go about doing the same thing in C#? Also, how long should I wait before I assume the user is done typing? 100ms?
If you're comfortable using the Reactive (Rx) framework, then you could implement this functionality using its built in throttling extremely quickly.
Here is an article on the subject: Rx Can Improve UI Responsiveness
And some code stolen & modified from the article:
var textObserver = (from text in Observable.FromEvent<TextChangedEventArgs>(_app.myTextField, "TextChanged")
select text).Throttle(TimeSpan.FromSeconds(.5));
_searchObserver = textObserver.Subscribe(textChangedEvent =>
{
var tb = (TextBox)textChangedEvent.Sender;
DoMySearch(tb.Text);
});
As stated in the article (which is worth reading in full), this will fire the code in the lambda expression whenever half a second elapses without the user typing anything.
I'll clean the example up tomorrow when I'm in front of my development PC, but this should give you a starting point now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With