function A {
*// Inside function A We have below lines of code to do debouncing*
const debounce = (func, delay) => {
let debounceTimer
return function() {
const context = this
const args = arguments
clearTimeout(debounceTimer)
debounceTimer
= setTimeout(() => func.apply(context, args), delay)
}
}
button.addEventListener('click', debounce(function() {
*// Some Code Will be Ecexuted here after 3000 ms*
}, 3000));
*// function A ends here*
}现在我想调用"clearTimeout(debounceTimer)“或任何其他可能的代码来清除另一个函数(函数B)中的去抖动超时。
function B {
*// How To Call "clearTimeout(debounceTimer)"???*
}发布于 2018-11-07 20:02:29
也许这可能会有所帮助:
function A(func) {
const obs$ = Observable.fromEvent(button, 'click')
.pipe(delay(debounceTime), map(args => func(args)));
return obs$;
}
// Now you are free to use observable in function B.
function B() {
const obs$ = A(/*your function*/);
obs$.subscribe(res => /*use result*/)
// Doing this will clear everything.
.unsubscribe(() => {});
}发布于 2018-11-07 20:12:30
让函数A返回一个对象,该对象提供清除超时句柄。
例如,像这样:
const button = document.getElementById("btn");
const cancel = document.getElementById("can");
const log = document.getElementById("log");
function A() {
const state = {
clear: () => null
}
const debounce = (func, delay) =>
(...args) => {
state.clear();
state.clear = clearTimeout.bind(null,
setTimeout(func.bind(null, ...args), delay));
};
button.addEventListener('click', debounce(function() {
log.textContent = "Message arrived at " + Date().match(/\d+:\d+:\d+/)
+ "\n" + log.textContent;
}, 3000));
return state;
}
function B(state) {
state.clear();
}
const state = A();
cancel.addEventListener('click', B.bind(null, state));<button id="btn">Send Message</button>
<button id="can">Abort Message</button>
<pre id="log"></pre>
https://stackoverflow.com/questions/53188104
复制相似问题