Javascript img change语句太火了

时间:2015-10-15 17:17:43

标签: javascript responsivevoice

我正在制作Nest的Smoke和一氧化碳警报巢保护模拟器。但是当我按下按钮(点击)时,内圈不会像预期的那样变成蓝色。它说话,因为我使用了ResponsiveVoice,但它只是没有点亮!这是我的(未完成的)代码。

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

1 个答案:

答案 0 :(得分:7)

你可以试试这个:

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";
        }
    );
}

使用setTimeout或setInterval会更好,因为大多数浏览器都使用单个线程进行javascript,当前函数会在页面等待时使页面无响应。这允许您异步执行其他操作。