我正在为免费代码营编写一个游戏,我需要眨眼次数。
这是我找到的解决方案,但看起来很难看:
function blinkTheCount(symbol) {
document.getElementById('count').innerHTML = '';
setTimeout(function() {
document.getElementById('count').innerHTML = symbol;
setTimeout(function() {
document.getElementById('count').innerHTML = '';
setTimeout(function() {
document.getElementById('count').innerHTML = symbol;
setTimeout(function() {
document.getElementById('count').innerHTML = '';
setTimeout(function() {
document.getElementById('count').innerHTML = symbol;
}, 200);
}, 200);
}, 200);
}, 200);
}, 200);
}
请你帮助我以更时尚的方式写一下吗?
我尝试使用for循环但是我进入页面挂起。
非常坦克。
答案 0 :(得分:3)
Thanks to everyone, now it's:
function blinkTheCount(symbol) {
var count = 0;
var blinkIt = setInterval(function () {
if (count++ === 5) {
clearInterval(blinkIt);
}
if (document.getElementById('count').innerHTML !== symbol) {
document.getElementById('count').innerHTML = symbol;
} else {
document.getElementById('count').innerHTML = '';
}
}, 200);
}
Have a nice day!
答案 1 :(得分:1)
setInterval
is probably what you would want to use in this case.
If you don't need to blank out the content of the container, perhaps try swapping between display: block and display: none for the same element. Just check the display status of the container each time and update accordingly.
var count = document.getElementById('count');
setInterval(function() {
count.style.display = count.style.display == 'none' ? 'block' : 'none';
}, 500);
<div id="count">3</div>
答案 2 :(得分:1)
I'll use setTimeout
here instead of setInterval
, not because it's the best option, but just to show the OP how he can control the number of blinks with setInterval
:
var max = 10, i = 0;
var myvalues = ["test", "TEST"];
(function loop(){
if(i++ > max) return;
var index = i%2;
setTimeout(function(){
document.getElementById('count').innerHTML = myvalues[index];
loop();
}, 200)
}());
Here is the fiddle: https://jsfiddle.net/gerardofurtado/joypdg6g/