Skip to content

Instantly share code, notes, and snippets.

@brianswisher
Last active July 12, 2019 13:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianswisher/380d754794f0e7a71f068f82bc2cbc43 to your computer and use it in GitHub Desktop.
Save brianswisher/380d754794f0e7a71f068f82bc2cbc43 to your computer and use it in GitHub Desktop.
Using form state & debounce with JavaScript
(() => {
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()
})()
@brianswisher
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment