0

Back in college I wrote a game where the computer would sleep for 1 second, wake up and check to see if anything needed to be processed. Of course, if the user entered a single character command, it would respond immediately.

Is there a way to do that with JavaScript?

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373

2 Answers2

2

setTimeout() and setInterval() will allow you to execute some code at regular intervals.

You can also monitor key press events in the DOM. Libraries like jQuery make this really easy with built in support for keyDown, keyUp and keyPress events. You can see these here: http://docs.jquery.com/Events

Rik Heywood
  • 13,816
  • 9
  • 61
  • 81
1
function processKeyCommand(){
  ...
}

document.onkeypress = processKeyCommand

function processEverythingEveryOneSecond(){
  ...
  setTimeout(function(){processEverythingEveryOneSecond()}, 1000)
}

processEverythingEveryOneSecond()

:))

Sergei Kovalenko
  • 1,402
  • 12
  • 17