Brad Martin Brad Martin - 1 year ago 160
Javascript Question

Execute Event after NativeScript Slider observable stops changing

I have a slider with the value bound to an observable, all works great there.

I've setup the

on the slider so I'm getting the event when the observable is changed (when the user drags the slider).

slider.on(Observable.propertyChangeEvent, function(data: PropertyChangeData) {
console.log('EventName: ' + data.eventName);
console.log('PropName: ' + data.propertyName);
console.log('Value: ' + data.value);

What I want:

I'd like to execute an event once the observable quits changing for a set period of time (example: 1000ms). To top it off, a way to stop this event if the observable starts changing again. I need to do some processing once the user sets the slider at its destination to update some other parts of the UI. So if the user starts changing it again, for performance purposes it might be best to STOP that processing and then execute once the changes are done by the user adjusting the slider.

I'm thinking set a variable and then start a timer but it's not really clicking right now for me :)

UPDATE with Answer

let underscore = require("underscore");

function debouncedValue(data: PropertyChangeData) {
console.log('NewSlider value: ' + data.value);

let debouncedSlider = underscore.debounce(debouncedValue, 800);

slider.on(Observable.propertyChangeEvent, debouncedSlider);


Answer Source

In UnderscoreJS you have a function called debounce that does exactly what you are trying to achieve here.

From the docs:

_.debounce(function, wait, [immediate])  

Creates and returns a new debounced version of the passed function which will postpone its execution until after wait milliseconds have elapsed since the last time it was invoked. Useful for implementing behavior that should only happen after the input has stopped arriving. For example: rendering a preview of a Markdown comment, recalculating a layout after the window has stopped being resized, and so on.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download