Javascript img 更改语句过早触发
Javascript img change statement fires too early
我正在制作 Nest 的烟雾和一氧化碳报警器 Nest Protect 模拟器。但是当我按下按钮(点击)时,内环并没有像预期的那样变成蓝色。它会说话,就像我使用 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>
你可以试试这个:
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 使用单线程,您当前的函数会使页面在等待时无响应。这允许您异步执行其他操作。
我正在制作 Nest 的烟雾和一氧化碳报警器 Nest Protect 模拟器。但是当我按下按钮(点击)时,内环并没有像预期的那样变成蓝色。它会说话,就像我使用 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>
你可以试试这个:
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 使用单线程,您当前的函数会使页面在等待时无响应。这允许您异步执行其他操作。