Search code examples
javascriptresponsivevoice

Javascript img change statement fires too early


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>

Solution

  • 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.