3

I'm making a simulator of the Smoke and Carbon Monoxide Alarm Nest Protect, by Nest. But when I press the button (click) the inner ring doesn't turn blue as it's supposed to. It speaks, as I used ResponsiveVoice, but it just doesn't light up! Here's my (unfinished) code.

<script src="http://code.responsivevoice.org/responsivevoice.js"></script>    
<script>
function delay(millis)  {
    var date = new Date();
    var curDate = null;
    do { curDate = new Date(); }
    while(curDate-date < millis);
}
function press() {
    document.getElementById("unit").src = "assets/img/blue.jpg";
    delay(500);
    responsiveVoice.speak("Ready. In the Living Room. Press to test.");
    delay(500);
    document.getElementById("unit").src = "assets/img/idle.jpg";


}
</script>
ry00000
  • 33
  • 5
  • 1
    You should really consider using `setTimeout` instead of a hard delay since JavaScript runs on a single thread, and if JavaScript execution is stuck in a while loop, the page will freeze. – yvesmancera Oct 15 '15 at 17:30

1 Answers1

7

You could try this:

function delay(millis, action)  {
    setTimeout(action, millis);
}

function press () {
    document.getElementById("unit").src = "assets/img/blue.jpg";
    delay(500,
        function () {
            responsiveVoice.speak("Ready. In the Living Room. Press to test.");
        }
    );
    delay(1000,
        function () {
            document.getElementById("unit").src = "assets/img/idle.jpg";
        }
    );
}

It's better to use setTimeout, or setInterval since most browsers use a single thread for javascript your current function will make the page unresponsive while it waits. This allows you to do other stuff asynchronously.

AtheistP3ace
  • 9,611
  • 12
  • 43
  • 43