js按键事件和未发生按键事件时的操作之间的间隔

Interval between js keypress events and action if keypress event is not occurring

本文关键字:事件 操作 之间 js      更新时间:2023-09-26

在我下面的代码中,在按键事件或1500毫秒后(如果没有按键),<div>中会显示不同的单词。单词出现和按键之间的经过时间是我的反应时间,它保存在变量reac中。

这一切都很好。但现在我想做两个调整:

  1. 如果没有按键,反应时间应等于1500。就像现在一样,时间一直持续到按下一个键。

  2. 我想要一个旧单词消失和新单词出现之间的间隔为500毫秒。

我认为它是setTimeoutsetInterval,但我试过了,结果从来都不完美。

这是我的脚本(我缩短了它,使它更可读,所以我可能忘记了在下面的例子中关闭一个括号-希望不要):

$(document).ready(function(){
  var upda = function() {
    (show random word in div)
  };
  t1 = (new Date()).getTime();
  timer = setInterval(upda, 1500);
  $(document).keypress(function(e){
    clearInterval(timer);
    var t2 = (new Date()).getTime();
    reac = t2 - t1;
    t1 = t2;
    if (e.keyCode == 97) {
      (show another random word in div)
    };
    timer = setInterval(upda, 1500);
  });
}); 

你不是真的想要一个间隔,你想要一个超时

一般的想法是,你设定1500米的有效期;如果用户在输入到期时还没有提供适当的输入,则超时将到期,超时功能将启动,设置默认的reac值并重新启动计时器。

然后,按键处理程序将缩短到期时间并记录"实际"reac

顺便说一句,您可能会意识到,对于任何类型的敏感计时操作,基于浏览器的JavaScript都是一个糟糕的选择,所以我们将继续假设这是针对真正准确的计时数据并不重要的用例。:)


编辑

作为练习,我重新编写了代码,使用计时器而不是间隔,并将任务划分为各个函数。这只是一个例子;其他开发人员可能会采取不同的方法。例如,在一个更大的项目中,它几乎肯定会被封装在一个对象库中,您可以在应用程序中重用该对象库。

var expectedInput, inputTimer, reac, startTime;
var $document = $(document);
var defaultReacTime = 1500;
var delayBetweenInputs = 500;
var timerInterval = 1500;
var showWordAndWaitForInput = function () {
    startTime = (new Date()).getTime();
    $document.on('keypress', keypressHandler);
    expectedInput = 97;
    console.log('Waiting for <expectedInput> at <startTime> ::', expectedInput, startTime);
    inputTimer = setTimeout(timerExpires, timerInterval);
};
var stopWaitingForInput = function () {
    clearTimeout(inputTimer);
    $document.off('keypress', keypressHandler);
};
var recordReacAndResetTimer = function (reactionTime) {
    reac = reactionTime;
    console.log('reac ::', reac);
    setTimeout(showWordAndWaitForInput, delayBetweenInputs);
};
var timerExpires = function () {
    stopWaitingForInput();
    console.log('timer expired');
    recordReacAndResetTimer(defaultReacTime);
};
var isInputValid = function (e) {
    return e.keyCode === expectedInput;
};
var keypressHandler = function (e) {
    console.log('input received ::', e.keyCode);
    if (isInputValid(e)) {
        console.log('input is valid, ask for new input');
        stopWaitingForInput();
        var endTime = (new Date()).getTime();
        recordReacAndResetTimer(endTime - startTime);
    } else {
        console.log('input is invalid, keep waiting');
    }
};
setTimeout(showWordAndWaitForInput, delayBetweenInputs);

希望这能有所帮助。