Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from debounced function in javascript? [duplicate]

I have a code like that:

var originalFunction = function() {
    return 'some value';
};

var debouncedFunction = _.debounce(originalFunction, 3000);

console.log('debouncedFunction() result: ', debouncedFunction());

console.log('originalFunction() result: ', originalFunction());

(codepen link)

And the result in the console is:

debouncedFunction() result:  undefined 

originalFunction() result:  some value

As you can see, the debounced function doesn't return anything. I understand that it's caused by an internal timer in the debounced function, but is there away around that?

like image 589
Victor Marchuk Avatar asked Jun 15 '16 13:06

Victor Marchuk


1 Answers

that's because debounced functions are called asynchronously - you can't return a value from them, although you can call another function passing the result:

var originalFunction = function() {
    console.log('some value');
    // or something like: callback(result)
};

var debouncedFunction = _.debounce(originalFunction, 3000);

console.log('debouncedFunction() result: ', debouncedFunction());
like image 181
pwolaq Avatar answered Oct 05 '22 04:10

pwolaq