title: keylistener doesn't work at the first
body: <p>My program is like a reaction game. When press the "up arrow" the background change the color to red. And you need the press the button whithin 2 sec. And if you don't press then you lose else the game is running on.  But at the first 2 seconds you lose anyway but the game is going on well. So what's the problem with the code at the first 2 seconds?</p>
  
  <p>My code:</p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>var ido = 2000;
  var nyomott = 0;
  var nemelso = 0;
  // &gt;&gt; main()
  function main() {
    nyomott = 0;
    var r = Math.floor(Math.random() * 4);
    var szin;
  
    switch (r) {
      case 0:
        szin = "red";
        break;
      case 1:
        szin = "green";
        break;
      case 2:
        szin = "yellow";
        break;
      case 3:
        szin = "blue";
        break;
    }
  
    var print = "&lt;h1&gt;" + "Pess the key: " + "&lt;/br&gt;" + szin + "&lt;/h1&gt;" + "&lt;/br&gt;";
    document.getElementById("results").innerHTML = print;
  
    startTimer();
  }
  
  var ciklus = setInterval(startTimer, ido);
  
  // &gt;&gt; startTimer() : This function starts the timer
  function startTimer() {
    timerId = setTimeout(function() {
      if (nyomott == 0) {
        document.getElementById("results").innerHTML = "&lt;h1&gt;Lose&lt;/h1&gt;";
        clearInterval(ciklus);
      } else {
        main();
      }
    }, ido);
  
  }
  
  document.addEventListener("keydown", function(inEvent) {
  
    if (inEvent.keyCode == 38) {
      document.body.style.backgroundColor = "red";
      nyomott = 1;
      console.log(nyomott);
    } else if (inEvent.keyCode == 404) document.body.style.backgroundColor = "green";
    else if (inEvent.keyCode == 405) document.body.style.backgroundColor = "yellow";
    else if (inEvent.keyCode == 406) document.body.style.backgroundColor = "blue";
  });</code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>body {
    width: 100%;
    height: 100%;
    background-color: #202020;
  }
  div {
    position: absolute;
    height: 100%;
    width: 100%;
    display: table;
    font-size: 60px;
    color: #ffffff;
  }
  h1 {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
    color: #FFFFFF;
  }</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div onload="main()" id="results"&gt;
    &lt;h1&gt;&lt;/h1&gt;
  &lt;/div&gt;</code></pre>
  </div>
  </div>
  </p>