Skip to content

Instantly share code, notes, and snippets.

@stevewadsworth
Last active July 22, 2018 19:29
Show Gist options
  • Select an option

  • Save stevewadsworth/6849fe62b91399a87f043b901a5cb2d0 to your computer and use it in GitHub Desktop.

Select an option

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
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