3

I'm trying to run a function when a model variable updates in my UI but I'm also trying to throttle how often the function is executed via a debounce as the requested function fires an AJAX call. However the debounce function below just doesn't seem to be firing at all.

I originally wrote my own debounce service and have resorted to using underscores debounce method to test whether what I wrote was incorrect or not but it turns out Angular just isn't liking something below...

Using Angular's ng-model-option debounce method in the HTML is not an option.

$scope.$watch('filters.monthlyCost', function () {

    _.debounce(function () {
        console.log('lol');
    }, 1000);

});

There are no console errors, console.log('lol') just never happens.

Note: $watch does execute.

leaksterrr
  • 3,800
  • 7
  • 34
  • 65

2 Answers2

1

Since debounce returns a function ((Function): Returns the new debounced function.) that return value of debounce needs to be executed,

i.e example:

_.debounce(function () {
        console.log('lol');
    }, 1000)();

You could do:

$scope.$watch('monthlyCost', _.debounce(function() {
        console.log('lol');
    }, 1000));
PSL
  • 123,204
  • 21
  • 253
  • 243
0

As I under stand from the docs of _.debounce (not tested)

$scope.$watch('filters.monthlyCost', function () {

    var logConsole = _.debounce(function () {
        console.log('lol');
        }, 1000);
    logConsole();

});

With your code, you are only registering a debounce function but it will not execute.

Alexander
  • 3,019
  • 1
  • 20
  • 24