0

Let's say I have a function that updates some internal states of the application:

def on_change(*args, **kwargs):
    pass  # some compute intensive state change

This function can run up to hundred times a second (due to many mousewheel events triggering the update) - I would only like to execute the above function once and only the last call should be executed.

What is the best design pattern for managing such a situation? The only way I can think of is spawning a separate thread for each on_change call and share a variable between them, but this sounds overly messy...

Thanks!

1

1 Answer 1

1
class Waiter:
    def __init__(self):
        self.args = ()
        self.kwargs = {}
        self.changed = False

    def on_change(self, *args, **kwargs):
        # This is the event handler
        # It does nothing but save the latest arguments
        self.args = args
        self.kwargs = kwargs
        self.changed = True

    def tick(self):
        # Call this function once per second, or whatever
        if self.changed:
            # Do your updates, using self.args and self.kwargs
            self.changed = False

Since you mentioned mouse events you are evidently writing a GUI application. All GUI engines, in my experience, have timers and the ability to call functions on a periodic basis. Use that capability to call tick periodically.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.