1

As the title, How can I run realtime function and debounce function in the same callback function such as

input.addEventListener('keyup', function () {
  realtimeFn()
  _.debounce(debounceFn, 1000) // how to code here...
})

function realtimeFn () { console.log(1) }


function debounceFn () { console.log(2) }

I want to log 1 every time and log 2 after all keyup and 1 second.

quietcoder
  • 155
  • 11

2 Answers2

3

Debounce returns a debounced function, you should be using that returned function instead of calling debounce. This code sample should do the thing.

var debounced = _.debounce(debounceFn, 1000) ;
input.addEventListener('keyup', function () {
  realtimeFn();
  debounced();
})

function realtimeFn () { console.log(1) }


function debounceFn () { console.log(2) }
Salketer
  • 14,263
  • 2
  • 30
  • 58
  • Thank you, and it seems that I need to read the source code of lodash.throttle and underscore.throttle. – quietcoder Aug 08 '17 at 14:22
  • Depends on what are your needs exactly. Read https://stackoverflow.com/questions/25991367/difference-between-throttling-and-debouncing-a-function – Salketer Aug 08 '17 at 14:25
-1

I suggest to use setInterval() and setTimeout():

input.addEventListener('keyup', function() {
    setInterval("realtimeFn()", 1000);
setTimeout("debounceFn()", 1000);
});
halfer
  • 19,824
  • 17
  • 99
  • 186
Tiefan Ju
  • 510
  • 3
  • 14