Skip to content

Add leading and trailing for throttle like in lodash #37

@yumauri

Description

@yumauri

Following this comment

To have more industry-like behaviour (lodash), throttle should provide options to indicate whether target should be triggered on the leading and/or trailing edge of the timeout.

leading [= true] (boolean): Specify triggering on the leading edge of the timeout
trailing [= true] (boolean): Specify triggering on the trailing edge of the timeout

If leading and trailing options are true, target is triggered on the trailing edge of the timeout only if the throttled source is triggered more than once during the timeout.

If timeout is 0 and leading is false, target triggering is deferred until to the next tick, similar to setTimeout with a timeout of 0.


const trigger = createEvent()

// by default `leading` is `true` and `trailing` is `true`
const throttled = throttle({ source: trigger, timeout: 100 })

trigger(1)

throttled should be triggered immediately, one time


const trigger = createEvent()

// by default `leading` is `true` and `trailing` is `true`
const throttled = throttle({ source: trigger, timeout: 100 })

trigger(1)
trigger(2)
trigger(3)

throttled should be triggered immediately with payload of 1 and second time after 100ms with payload of 3


const trigger = createEvent()
const throttled = throttle({ source: trigger, timeout: 100, leading: false })
trigger(1)

throttled should be triggered after 100ms, one time


const trigger = createEvent()
const throttled = throttle({ source: trigger, timeout: 100, leading: false })
trigger(1)
trigger(2)
trigger(3)

throttled should be triggered after 100ms, one time, with payload of 3 (just like current behaviour)


const trigger = createEvent()
const throttled = throttle({ source: trigger, timeout: 0, leading: false })
trigger(1)

throttled should be triggered on the next tick, one time (just like current behaviour)


const trigger = createEvent()
const throttled = throttle({ source: trigger, timeout: 100, trailing: false })

trigger(1)
await wait(75)
trigger(2)
await wait(75)
trigger(3)

throttled should be triggered immediately with payload of 1 and second time after 150ms with payload of 3


With combination leading: false, trailing: falsethrottled should not be triggered at all


Playground with lodash's throttle

Metadata

Metadata

Assignees

No one assigned

    Labels

    RFCSome new feature that should be discussedgood first issueGood for newcomers

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions