summaryrefslogtreecommitdiff
path: root/src/mbgl/util/throttler.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/mbgl/util/throttler.cpp')
-rw-r--r--src/mbgl/util/throttler.cpp36
1 files changed, 36 insertions, 0 deletions
diff --git a/src/mbgl/util/throttler.cpp b/src/mbgl/util/throttler.cpp
new file mode 100644
index 0000000000..910810ce2f
--- /dev/null
+++ b/src/mbgl/util/throttler.cpp
@@ -0,0 +1,36 @@
+#include <mbgl/util/throttler.hpp>
+
+namespace mbgl {
+namespace util {
+
+Throttler::Throttler(Duration frequency_, std::function<void()>&& function_)
+ : frequency(frequency_)
+ , function(std::move(function_))
+ , pendingInvocation(false)
+ , lastInvocation(TimePoint::min())
+{}
+
+void Throttler::invoke() {
+ if (pendingInvocation) {
+ return;
+ }
+
+ Duration timeToNextInvocation = lastInvocation == TimePoint::min()
+ ? Duration::zero()
+ : (lastInvocation + frequency) - Clock::now();
+
+ if (timeToNextInvocation <= Duration::zero()) {
+ lastInvocation = Clock::now();
+ function();
+ } else {
+ pendingInvocation = true;
+ timer.start(timeToNextInvocation, Duration::zero(), [this]{
+ pendingInvocation = false;
+ lastInvocation = Clock::now();
+ function();
+ });
+ }
+}
+
+} // namespace util
+} // namespace mbgl