Skip to content

Instantly share code, notes, and snippets.

@KristofferK
Created November 17, 2017 20:44
Show Gist options
  • Save KristofferK/23279165e0d942ac4d84d8c114e3cc9a to your computer and use it in GitHub Desktop.
Save KristofferK/23279165e0d942ac4d84d8c114e3cc9a to your computer and use it in GitHub Desktop.
debounceTime using setTimeout, rxjs and value matching
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>Hej</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.0/Rx.min.js"></script>
</head>
<body>
<input id="input" type="text"/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<pre>Output 1: <span id="keystrokeOutput1"></span></pre>
<pre>Output 2: <span id="keystrokeOutput2"></span></pre>
<pre>Output 3: <span id="keystrokeOutput3"></span></pre>
<script>
(method1 = () => {
const e = document.getElementById('keystrokeOutput1');
const i = document.getElementById('input');
let timeouter;
i.addEventListener('keydown', () => {
clearTimeout(timeouter);
timeouter = window.setTimeout(() => {
e.innerText = i.value;
}, 400);
});
})();
(method2 = () => {
const e = document.getElementById('keystrokeOutput2');
const i = document.getElementById('input');
const i$ = Rx.Observable.fromEvent(i, 'keydown');
i$.debounceTime(400).subscribe(evt => e.innerText = i.value);
})();
(method3 = () => {
const clickManager = (() => {
let clicks = 0;
return {
addClick: () => ++clicks,
getClicks: () => clicks
};
})();
const e = document.getElementById('keystrokeOutput3');
const i = document.getElementById('input');
let lastVal = "";
i.addEventListener('keydown', () => {
let supposedClickCount = clickManager.addClick();
window.setTimeout(() => {
if (lastVal == i.value.trim()) {
console.log("Not searching due to no changes");
}
else if (supposedClickCount == clickManager.getClicks()) {
e.innerText = lastVal = i.value.trim();
console.log("Searching :D");
}
else {
console.log("Not searching due to mismatch", clickManager.getClicks(), "vs", supposedClickCount);
}
}, 400);
});
})();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment