throttle & debounce
<div class="input-wrap">
<label for="type">Type </label>
<select id="type" >
<option value="throttle">throttle</option>
<option value="debounce">debounce</option>
</select>
</div>
<div class="input-wrap">
<label for="delay">딜레이</label>
<input id="delay" type="number" value="500"/>
<span>(ms)</span>
</div>
<div class="input-wrap">
<label for="search">Input Test</label>
<textarea id="search" rows="5"></textarea>
</div>
<div id="log">
<p>---------- type : throttle ----------</p>
<p>---------- delay : 500ms ----------</p>
</div>
const searchInput = document.querySelector('#search')
const delayType = document.querySelector('select#type')
const inputLog = document.querySelector('#log')
const delayInput = document.querySelector('#delay')
const throttling = (func,delay) => {
let timer;
return (...args) => {
if (!timer) {
timer = setTimeout(function() {
timer = null;
func(...args)
}, delay);
}
}
}
const debounce = (func,delay) => {
let timer;
return (...args) => {
clearTimeout(timer)
timer = setTimeout(function() {
func(...args)
}, delay)
}
}
const search = () => {
const log = `input : ${searchInput.value}`
inputLog.innerHTML += `<p>${log}</p>`
inputLog.scrollTop = inputLog.scrollHeight
}
let throttledEvent = throttling(search,500)
let debouncedEvent = debounce(search,500)
delayInput.addEventListener('change',(e)=> {
throttledEvent = throttling(search,Number(e.target.value))
debouncedEvent = debounce(search,e.target.value)
searchInput.value = ''
inputLog.innerHTML += `<p>------- delay : ${e.target.value}ms ----------</p>`
inputLog.scrollTop = inputLog.scrollHeight
})
delayType.addEventListener('change', (e)=> {
searchInput.value = ''
inputLog.innerHTML += `<p>------- type : ${e.target.value} ----------</p>`
inputLog.scrollTop = inputLog.scrollHeight
})
searchInput.addEventListener('keydown', (e)=> {
const type = delayType.value
if (type === 'throttle') {
throttledEvent(e)
} else {
debouncedEvent(e)
}
})
#log {
border : 1px solid black;
width : 80%;
height : 300px;
overflow-y: scroll;
}
#log p {
margin : 8px;
}
.input-wrap {
vertical-align: text-bottom;
display:flex;
font-size : 16px;
align-items:center;
margin: 8px;
}
.input-wrap label {
text-align: center;
width : 100px;
}
.input-wrap select,.input-wrap input {
width : 100px;
height: 30px;
box-sizing:border-box;
}
#search {
width : 500px;
resize:none;
}