Last active
July 12, 2019 13:49
-
-
Save brianswisher/380d754794f0e7a71f068f82bc2cbc43 to your computer and use it in GitHub Desktop.
Using form state & debounce with JavaScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(() => { | |
const test = (result, expect) => | |
`${result === expect && '✅' || '🔴'} ${expect}:${result}` | |
const mkRestore = (input, state) => { | |
return () => { | |
state.names.pop() | |
input.value = state.names[state.names.length - 1] || '' | |
} | |
} | |
//----------------------------------------- | |
const input = {} | |
const state = {names: ['a', 'b', 'c']} | |
const restore = mkRestore(input, state) | |
restore() | |
console.log(test(state.names[state.names.length - 1], 'b')) | |
restore() | |
console.log(test(input.value, 'a')) | |
//----------------------------------------- | |
const debounceInput = (input, delay, state) => { | |
clearTimeout(state.capture) | |
state.capture = setTimeout(() => { | |
state.names.push(input.value) | |
}, delay) | |
} | |
//----------------------------------------- | |
const delay = 500 | |
input.value = 'hello' | |
debounceInput(input, delay, state) | |
console.log(test(state.names.length, 1)) | |
setTimeout(() => { | |
console.log(test(state.names.length, 2)) | |
}, delay * 1.5) | |
//----------------------------------------- | |
const mkForm = () => { | |
const form = document.createElement("form") | |
const { body } = document | |
form.innerHTML = ` | |
<table style="margin: 20px"> | |
<tr> | |
<td> | |
<label for="name">name</label> | |
</td> | |
</tr> | |
<tr> | |
<td> | |
<input id="name" name="name" value="" /> | |
</td> | |
</tr> | |
<tr> | |
<td> | |
<button name="restore" style="background-color: red; color; white; padding: 4px">Reset</button> | |
</td> | |
</tr> | |
</table> | |
` | |
form.onsubmit = () => false | |
body.innerHTML = '' | |
body.appendChild(form) | |
const STATE = { names: [] } | |
const nameInput = document.forms[0].name | |
document.forms[0].restore.onclick = mkRestore(nameInput, STATE) | |
nameInput.onkeyup = () => { | |
debounceInput(nameInput, 1000, STATE) | |
} | |
} | |
mkForm() | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://youtu.be/4Ig9zf7sX94