@ideal-postcodes/jsutil
Version:
Browser Address Autocomplete for api.ideal-postcodes.co.uk
51 lines (50 loc) • 1.3 kB
JavaScript
import { debounce } from "./debounce";
export const watchTimer = ({ bind, interval = 1000 }) => {
let timer = null;
const start = () => {
timer = window.setInterval(() => {
try {
bind();
}
catch (e) {
stop();
}
}, interval);
return timer;
};
const stop = () => {
if (timer === null)
return;
window.clearInterval(timer);
timer = null;
};
return { start, stop };
};
export const watchMutation = ({ bind, interval = 1000, target = window.document, observerConfig = {
subtree: true,
childList: true,
}, }) => {
const observer = new MutationObserver(debounce(() => {
try {
bind();
}
catch (e) {
stop();
}
}, interval));
const start = () => {
observer.observe(target, observerConfig);
return null;
};
const stop = () => observer.disconnect();
return { start, stop };
};
export const watchChange = (options) => {
if (!window)
return watchTimer(options);
if (!window.MutationObserver)
return watchTimer(options);
if (options.mutationObserver)
return watchMutation(options);
return watchTimer(options);
};