Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- </head>
- <body>
- <input type="text"><br>
- default: <span id="default"></span><br>
- debounce: <span id="debounce"></span><br>
- throttle: <span id="throttle"></span><br>
- </body>
- <script>
- function debounce(callbackFn, time) {
- let timeOutObj;
- return (...args) => {
- clearTimeout(timeOutObj);
- timeOutObj = setTimeout(() => {
- callbackFn(...args);
- }, time);
- }
- }
- function throttle(callbackFn, time) {
- let waiting = false;
- let waitingArgs;
- const timeOutFn = () => {
- if (waitingArgs == null) {
- waiting = false;
- } else {
- callbackFn(waitingArgs);
- waitingArgs = null;
- setTimeout(timeOutFn, time);
- }
- }
- return (...args) => {
- if (waiting) {
- waitingArgs = args;
- return;
- }
- callbackFn(...args);
- waiting = true;
- setTimeout(timeOutFn, time);
- }
- }
- const input = document.querySelector('input');
- const defElem = document.querySelector('#default');
- const debElem = document.querySelector('#debounce');
- const thrElem = document.querySelector('#throttle');
- input.focus();
- const updateDeb = debounce(text => {
- debElem.innerHTML = text;
- }, 2000);
- const updateThr = throttle(text => {
- thrElem.innerHTML = text;
- }, 750);//*/
- input.addEventListener('input', e => {
- defElem.innerHTML = e.target.value;
- updateDeb(e.target.value);
- updateThr(e.target.value);
- })
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement