Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

brianswisher commented Jul 12, 2019

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.