-1

I'm trying to implement debounce from underscore library within setTimeout.

setInterval(function() {
  setTimeout(function(){   
    _.debounce(function() {
      console.log('debounce');
    }, 500);
  }, 1000);
}, 100);

Basically, console.log('debounce') should be called once in 500ms but it seems there's no output at all in the console.

JS Bin for testing: http://jsbin.com/beqisuruwu/edit?js,output

Thanks in advance.

RubyCat
  • 155
  • 11
  • 2
    k.. what is the problem? – Gogol Oct 19 '16 at 08:59
  • @Gogol no output in the console. So, 'debounce' is not printed out – RubyCat Oct 19 '16 at 09:05
  • 1
    did you include underscore library before calling the script? Also, try attaching it to an event.. e.g. window load or something.. – Gogol Oct 19 '16 at 09:08
  • I did include the library, I can get the value of `_.VERSION` – RubyCat Oct 19 '16 at 09:10
  • 1
    Ok. try running the script after dom is loaded.. like following http://stackoverflow.com/a/21814964/1437261 – Gogol Oct 19 '16 at 09:11
  • Doesn't seem to be working http://jsbin.com/wogumujahi/edit?js,output – RubyCat Oct 19 '16 at 09:16
  • 1
    Ok, it seems that debounce does not support anonymous functions.. see this answer... http://stackoverflow.com/a/24309963/1437261 basically, define the function and pass it to debounce and see if that works. – Gogol Oct 19 '16 at 09:19
  • 1
    debounce returns a function which is not called in your code. Create the debounced function outside the `setInterval` e.g. `var myFn = debounce(...)` and call it within the `setTimeout`: `myFn();` – Gruff Bunny Oct 19 '16 at 11:25
  • 1
    Why use a `setTimeout` and `debounce`? [Underscore's Debounce is a setTimeout](http://underscorejs.org/docs/underscore.html#section-83)... – evolutionxbox Oct 19 '16 at 11:37

1 Answers1

0

Are you sure you need function after setTimeout? Because _.debounce is a function itself. I am not sure either )) but code below works for me:setInterval(function() { setTimeout( _.debounce(function() { console.log('debounce'); }, 500) , 1000); }, 100);

AlBears
  • 1
  • 1