@rooks/use-timeout-when
Version:
Takes a callback and fires it when a condition is true
36 lines (32 loc) • 1.33 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react')) :
typeof define === 'function' && define.amd ? define(['react'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.useTimeoutWhen = factory(global.React));
}(this, (function (react) { 'use strict';
/**
* A setTimeout hook that calls a callback after a timeout duration
* when a condition is true
* @param cb The callback to be invoked after timeout
* @param timeoutDelayMs Amount of time in ms after which to invoke
* @param when The condition which when true, sets the timeout
*/
function useTimeoutWhen(cb, timeoutDelayMs = 0, when = true) {
const savedRefCallback = react.useRef();
react.useEffect(() => {
savedRefCallback.current = cb;
});
function callback() {
savedRefCallback.current && savedRefCallback.current();
}
react.useEffect(() => {
if (when) {
const timeout = window.setTimeout(callback, timeoutDelayMs);
return () => {
window.clearTimeout(timeout);
};
}
}, [when]);
}
return useTimeoutWhen;
})));
//# sourceMappingURL=index.js.map