[英]Detect time lapse between two key press in Javascript
我正在学习javascript,同时尝试创建一个简单的脚本,该脚本允许您使用键盘在Web浏览器中键入外语。
所以,当你键入a
例如,有映射到一个单个字母,所以单个字符Դ
会出现,然而,为了使人物像厄
出现,你必须输入两次,因为这种语言比英语更多的字符字母。
因此,问题在于最后一个字符。 通常,我必须在一秒钟的时间范围内连续键入g
和h
才能生成厄
字母,但是我在等待检查是否彼此之间在一秒钟内键入两个字符以显示该字母时遇到问题。
因此,我认为时间间隔函数不是解决此问题的方法,但是我也看不到任何其他方法。
就像Alex提到的那样,每按一次,都只需存储new Date().getTime();
在变量中,它将为您提供最新的UTC时间。 UTC时间以毫秒为单位,因此在下一次按键时,只需查看当前时间和存储的时间是否相差1000即可!
下面是示例代码,用于测量任意两个事件之间经过的时间。 我添加了setTimeout
只是为了给您一个示例。
var startTime = Date.now(); setTimeout(function(){ var elapsedTime = Date.now() - startTime; console.log('elapsedTime ='+elapsedTime); }, 100);
注意事项:检查keydown()中的键是否向上并通知keydown keypress()中的键是否已向上键;
var start = null; $('#in').keydown(function (e) { if (!start) {//checking is a new user input start = $.now(); } }).keyup(function (e) { var timeElapsed = $.now() - start; start = null;//start the next timing tracking console.log(['time elapsed:', timeElapsed, 'ms'].join(' ')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <h2>please input some letter to test</h2> <input id="in"/> </label>
关于您问题的另一个答案,也许这是您真正的答案。
function duration(timestamps) { var last = timestamps.pop(); var durations = []; while (timestamps.length) { durations.push(last - (last = timestamps.pop())); } return durations.reverse(); } function display(mills) { if (mills > 1000) return (mills / 1000) + ' s'; return mills + ' ms'; } var durations = []; $('#in').keydown(function (e) { durations.push($.now()); }).keyup(function (e) { var current = durations; current.push($.now()); durations = []; var timeElapsed = current[current.length - 1] - current[0]; console.log([ ['time elapsed:', display(timeElapsed)].join(' '), ['keys duration:', duration(current).map(display)].join(' ') ].join(' --- ')); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <h2>Please input something to test!</h2> <input id="in"/> </label>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.