S
S
Shimpanze2018-02-12 06:24:22
JavaScript
Shimpanze, 2018-02-12 06:24:22

JavaScript: why is the function not working?

Hello!
I can't figure out how the timer reset works clearTimeout(). Wrote a simple snippet, with the following algorithm:
1. After each key press - the timer starts and the countdown starts for 2 seconds;
2. after each subsequent pressing - the timer is reset and starts counting again;
3. if there were no clicks for more than 2 seconds, we output a message to the console.
The snippet itself:

function a() {
  // сначала сбрасываем таймер
  clearTimeout(timer);

  // если нажатий небыло больше чем 2 секунды - запускаем выполнение функции
  var timer = setTimeout(function() { 
    console.log('Выполнение...');
    return false; // почему здесь не срабатывает false и сообщение выводится 100 раз?
  }, 2000);
}

document.getElementById('content').addEventListener('keyup', a);

Example
I would appreciate a simple explanation.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Arman, 2018-02-12
@Shimpanze

And if

var timer;
function a() {
  !timer || clearTimeout(timer);
  timer = setTimeout(function() { 
    console.log('Выполнение...');
  }, 2000);
}

document.getElementById('content').addEventListener('keyup', a);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question