Skip to content

Instantly share code, notes, and snippets.

@sashee
Created August 5, 2019 16:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sashee/c09fb77c27ae9134e9b0ee8af6b7e8e6 to your computer and use it in GitHub Desktop.
Save sashee/c09fb77c27ae9134e9b0ee8af6b7e8e6 to your computer and use it in GitHub Desktop.
// https://codeburst.io/throttling-and-debouncing-in-javascript-b01cad5c8edf
const throttle=(t,e)=>{let n,o;return function(){const a=this,c=arguments;o?(clearTimeout(n),n=setTimeout(function(){Date.now()-o>=e&&(t.apply(a,c),o=Date.now())},e-(Date.now()-o))):(t.apply(a,c),o=Date.now())}};
const form = document.querySelector("form");
form.addEventListener("submit", (e) => e.preventDefault());
form.querySelector("input[type=submit]").style.display = "none";
[...document.querySelectorAll("form ~ *")].filter((e) => e.id !== "diagram").forEach((e) => e.remove());
let lastReq = undefined;
const observer = new MutationObserver(throttle(async () => {
const currentTime = new Date().getTime();
lastReq = currentTime;
form.querySelector("input[type=submit]").click();
const value = document.querySelector("textarea").value;
const html = await (await fetch("/form", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: `text=${encodeURIComponent(value)}`
})).text();
if (lastReq === currentTime) {
document.querySelector("#diagram img").src =
new DOMParser()
.parseFromString(html, 'text/html')
.querySelector("#diagram img")
.src;
}
}
, 200));
observer.observe(form, {
attributes: false,
childList: true,
subtree: true
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment