Skip to content

Instantly share code, notes, and snippets.

@sashee sashee/script.js
Created Aug 5, 2019

Embed
What would you like to do?
// 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
You can’t perform that action at this time.