Question: I need to write in a pure JavaScript function which will execute only for 5 seconds and will stop if either one of the following conditions (whichever comes first)

1. 5 seconds has elapsed
2. user inputted a field

I could only do condition 2 but can't figure out how to break the loop after 5 seconds:

```
function beginScanningForItemVer2(){
    var userInput= false;
    var element;
    while (!userInput){
        element = document.getElementById("input").value;
        if (element != null){
            userInput= true;
        }
    }
}

```

EDIT:

Thanks guys for helping me. Please keep helping me...
It seems I cannot use a while loop for detecting user input because my CPU usage goes up really fast while on the loop. Is there any way to accomplish both of these? Please help me

Answer: 
Javascript tends to be very callback oriented, since by default all the Javascript on a page runs in a single thread, which means that the UI isn't responsive while other code is busy running. So rather than looping in a function and looking for input on each loop, you likely want to register a callback function which will be called when your input element experiences a change -- for example, the `onchange` listener will run your callback whenever the value of the element changes. You could unregister this callback 5 seconds later to stop anything from happening if the user inputs something after the 5 seconds are up.

Sparse example (referencing <http://www.w3schools.com/jsref/event_onchange.asp>):

```
// Set a function to be called when the value of the input element changes.
object.onchange = function() { 
  valueAfterChange = document.getElementById("input").value;
  // Do something with valueAfterChange.
}

// window.setInterval calls a function after a set delay.
window.setInterval(function() { 
  object.onchange = null;
  // Anything else you might want to do after 5 seconds.
}, 5000);   // Call this function after 5000 milliseconds == 5 seconds.

```
**Eddited**

You could combine `setInterval` and `setTimeout` to solve . Your code will look like this.

```
var interval = setInterval(function() {
    var userInput= false;
    var element;
    while (!userInput){
        element = document.getElementById("input").value;
        if (element != null){
            userInput= true;
        }
    }
}, 1000);

setTimeout(function() {
    clearInterval(interval);
}, 5000)

```

You could see more information here. Cheers.

<https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers>