[英]Calling function with setTimeout in rapid fashion
I want the backgroundColor of a div to change for 250ms, and then change back. 我希望div的backgroundColor更改250ms,然后再更改回。 for this I use the following code as onclick on the div:
为此,我将以下代码用作div的onclick:
function keyAnimation(key) {
basicColor = key.style.backgroundColor;
key.style.backgroundColor = "red";
setTimeout(function () {
key.style.backgroundColor = basicColor;
}, 250);
But when I click the div multiple times quickly (within the 250ms) it remains red. 但是,当我快速单击div多次(在250ms内)时,它仍然为红色。 How can I code this so it will always go back to the basicColor after 250ms?
我该如何编码,使其在250ms之后始终返回basicColor?
Add a flag that blocks additional keypresses: 添加一个阻止其他按键的标志:
var running = false;
function keyAnimation(key) {
if(running) return;
running = true;
const basicColor = key.style.backgroundColor;
key.style.backgroundColor = "red";
setTimeout(function () {
key.style.backgroundColor = basicColor;
running = false;
}, 250);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.