функция debounce не работает в javascript - PullRequest
0 голосов
/ 07 августа 2020

У меня проблемы с пониманием, почему приведенный ниже код устранения неполадок не работает?

вы можете увидеть следующий код: ссылка

`
HTML:

<input type="text" onkeyup="betterFunction(event)"/>

JS:

let newValue;
let counter = 0;
const getData = () => {
    // dummy call to API and get Data
    console.log("Fetching Data ..", newValue,counter++);
}

const debounce = function (fn, d) {
    let timer;
    return function () {
        clearTimeout(timer);
        timer = setTimeout(() => {
            fn();
        }, d);
   }
}

const betterFunction = ({target:{value}}) => {
    newValue=value;
    debounce(getData, 2000); // **line 1**. placing this line of code debouncing does not happen
  
    intermediate()  // **line 2**. replacing this line of code with the above line debouncing works
}

const intermediate = debounce(getData, 2000);

`

Я понимаю, что функция debounce возвращает другую функцию, которая действует как закрытие в JavaScript, но почему приведенный выше код строки 1 не работает, а код строки 2 работает

Ответы [ 2 ]

2 голосов
/ 07 августа 2020
Функция

debounce возвращает функцию, которая никогда не вызывается, когда вы вызываете debounce как

debounce(getData, 2000);

dobounce, функция не должна возвращать функцию. Вам просто нужно выполнить следующие шаги для реализации функции debounce:

  1. Проверьте, не определено ли timer. Если нет, это означает, что существует тайм-аут, который нам нужно отменить.

  2. После этого установите новый таймер, вызвав setTimeout(), который вызывает данную функцию после указанного c количества времени .

Кроме того, timer не должно быть локальной переменной, потому что вы не хотите, чтобы она сбрасывалась всякий раз, когда вызывается функция debounce.

let counter = 0;
let newValue;
let timer;

const getData = () => {
  console.log("Fetching Data ..", newValue, counter++);
}

const debounce = function(fn, d) {
  if (timer) {
    clearTimeout(timer);
  }

  timer = setTimeout(fn, d);
}

const betterFunction = (e) => {
  newValue = e.target.value;
  debounce(getData, 2000);
}
<input type="text" onkeyup="betterFunction(event)" />

Если вы не хотите объявлять timer как глобальную переменную и хотите вернуть функцию из функции debounce, тогда вам нужно вызвать функция debounce один раз изначально, и всякий раз, когда событие keyup срабатывает в элементе input, вы вызываете функцию, возвращенную функцией debounce, вместо вызова функции debounce.

let counter = 0;
let newValue;

const getData = () => {
  console.log('Fetching Data ..', newValue, counter++);
};

const debounce = function(fn, d) {
  let timer;
  
  return function() {
    if (timer) {
      clearTimeout(timer);
    }

    timer = setTimeout(fn, d);
  };
};

const intermediate = debounce(getData, 2000);

const betterFunction = (e) => {
  newValue = e.target.value;
  intermediate();
};
<input type="text" onkeyup="betterFunction(event)" />
0 голосов
/ 07 августа 2020

надеюсь, что вы хотите:

let counter = 0;
// you need to define timer and newValue here first
let timer , newValue;

// defining input as varible for good usage better than usage in html
var input = document.querySelector("#inp");

const getData = () => {
    // increment first better than in console :)
    counter+=1;
    console.log("Fetching Data .." , newValue , counter);

    // as last step clear timer for next timeout
    clearTimeout(timer);
}

// givin value direct to timer directlly worked better than return
const debounce = function (fn, d) {
    timer = setTimeout(fn, d);
}


const betterFunction = () => {
    // newvalue must equal input value
    newValue = input.value;
    // and then calling debounce as last step
    debounce(getData, 2000);
}

// here giving onkeyup event to input for getting values and start working :)
input.onkeyup = betterFunction;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...