Last active
July 22, 2018 19:29
-
-
Save stevewadsworth/6849fe62b91399a87f043b901a5cb2d0 to your computer and use it in GitHub Desktop.
Throttle the rate at which a function is called to no more than the given rate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import android.os.Handler | |
| /** | |
| * Throttle the rate at which a function is called | |
| */ | |
| fun throttle(function: () -> Unit, rate: Long): () -> Unit { | |
| var throttled = false | |
| var called = false | |
| fun emit() { | |
| if (called) { | |
| function() | |
| called = false | |
| throttled = true | |
| //Timer().schedule(timerTask { emit() }, rate) // Use this when not Android | |
| Handler().postDelayed({ emit() }, rate) // Use this on Android | |
| } else { | |
| throttled = false | |
| } | |
| } | |
| return { | |
| called = true | |
| if (!throttled) { | |
| emit() | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment