javascript - How to detect intervals between keydowns in plain js -


i have tried detect interval between keydowns on div this:

window.onload = function() { var p = document.getelementbyid('input');     p.addeventlistener('keydown', function() {          if (document.queryselector('.rps')) {             p.removeattribute('class')             clearinterval('me')         }          if (!document.queryselector('.rps')) {             p.setattribute('class', 'rps')             var me = setinterval('interval()', 10)         }      }, false)  } var z = 0; function interval() {     z += 1 document.getelementbyid('isp').innerhtml = z; } 

html:

test

the problem , start interval() on first key press, not remove class rps required determine whether start or end setinterval.

the solution should in plain js - , work on more 1 keypress.

don't use setinterval. doing every n milliseconds.

you want when key pressed.

bind keydown event handler environment (or element interested in if want limit it).

inside handler, create new date() , store in local variable.

in particular variable outside scope of event handler exists: compare times of them. (this happen every keydown except first).

copy value of local variable on value of 1 wider scope.

function createhandler() {    var last_keydown_time;        function keydown_handler(event) {      var this_keydown_time = new date();      if (last_keydown_time) {        console.log(this_keydown_time - last_keydown_time);      }      last_keydown_time = this_keydown_time;    }        return keydown_handler;  }    addeventlistener('keydown', createhandler());
<input />


Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -