/* * index.js - Pajenerator client code */ // State var generating = false; var names = []; var flashcount = 0; var flashinterval; // Needed elements let root; let btn; let out; function onready() { root = document.querySelector("html") btn = document.querySelector("#btn"); out = document.querySelector("#name-box"); } // Returns the names from the API - as many as are configured. function get_names(onget) { const error_response = ["Errar", "Prablem"]; const uri = "/api"; let req = new XMLHttpRequest(); req.onreadystatechange = function() { if (this.readyState == 4) { if (this.status != 200) { onget(error_response); } try { let arr = JSON.parse(this.responseText) onget(arr); } catch { console.log("bad json: "+this.responseText) onget(error_response); } } } req.open("GET", uri, true); req.send(); } /* * 0.2x + 0.2e^(x-27) * where: * x - nth iteration * returns - time in seconds */ function timeout(i) { return (0.2*i) + (0.2*Math.exp(i - 27)); } function cleanup_generate() { // Reset button text (partially) btn.textContent = "Do the needful"; btn.disabled = true; // Reset cursor root.classList.remove("loading"); btn.classList.remove("loading"); out.classList.remove("loading"); flashinterval = setInterval(() => { out.classList.toggle("highlight"); if (flashcount++ >= 6) { flashcount = 0; generating = false; names = []; clearInterval(flashinterval); out.classList.remove("highlight"); btn.disabled = false; } }, 500) } function run_generate() { for (let i = 0; i < names.length; i++) { setTimeout(() => { out.value = names[i]; if (i == names.length - 1) { cleanup_generate(); } }, 1000*timeout(i)); } } function pull_names(arr) { names = names.concat(arr); if (names.length >= 30) { run_generate(); } else { get_names(pull_names) } } function generate() { if (generating) return; generating = true; // Button text btn.textContent = "Ok sar...!"; // Cursors root.classList.add("loading"); btn.classList.add("loading"); out.classList.add("loading"); get_names(pull_names); }