JSFiddle - React, Tailwind, and code Playground

by Palpatim

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);