From 39284e1d0f5a3c7664bce3b55e49bc3fe09c2276 Mon Sep 17 00:00:00 2001 From: jules Date: Mon, 6 Mar 2017 15:05:14 +0000 Subject: [PATCH] Added static method Timer::callAfterDelay() to invoke a one-shot lambda function --- modules/juce_events/timers/juce_Timer.cpp | 26 +++++++++++++++++++++++ modules/juce_events/timers/juce_Timer.h | 5 +++++ 2 files changed, 31 insertions(+) diff --git a/modules/juce_events/timers/juce_Timer.cpp b/modules/juce_events/timers/juce_Timer.cpp index 60035de973..9b6d2cc27d 100644 --- a/modules/juce_events/timers/juce_Timer.cpp +++ b/modules/juce_events/timers/juce_Timer.cpp @@ -348,3 +348,29 @@ void JUCE_CALLTYPE Timer::callPendingTimersSynchronously() if (TimerThread::instance != nullptr) TimerThread::instance->callTimersSynchronously(); } + +#if JUCE_COMPILER_SUPPORTS_LAMBDAS +struct LambdaInvoker : private Timer +{ + LambdaInvoker (int milliseconds, std::function f) : function (f) + { + startTimer (milliseconds); + } + + void timerCallback() override + { + auto f = function; + delete this; + f(); + } + + std::function function; + + JUCE_DECLARE_NON_COPYABLE (LambdaInvoker) +}; + +void JUCE_CALLTYPE Timer::callAfterDelay (int milliseconds, std::function f) +{ + new LambdaInvoker (milliseconds, f); +} +#endif diff --git a/modules/juce_events/timers/juce_Timer.h b/modules/juce_events/timers/juce_Timer.h index 7e9c27771c..94ae7448e1 100644 --- a/modules/juce_events/timers/juce_Timer.h +++ b/modules/juce_events/timers/juce_Timer.h @@ -121,6 +121,11 @@ public: */ int getTimerInterval() const noexcept { return timerPeriodMs; } + //============================================================================== + #if JUCE_COMPILER_SUPPORTS_LAMBDAS + /** Invokes a lambda after a given number of milliseconds. */ + static void JUCE_CALLTYPE callAfterDelay (int milliseconds, std::function functionToCall); + #endif //============================================================================== /** For internal use only: invokes any timers that need callbacks.