[英]Javascript - setTimeout/setInterval execute countdown before the function
I have a timer which triggers a function each 3 seconds using setTimeout or setInterval. 我有一个计时器,它使用setTimeout或setInterval每3秒触发一次函数。 The point is that I need to execute the countdown before the function instead of execute the function first and then the timer.
关键是我需要在函数之前执行倒计时,而不是先执行函数然后再执行计时器。
This is the code: 这是代码:
var timer;
document.getElementById('myBtn').addEventListener('mousedown', function (){
timer = setInterval(alert("Ey, release the button!"), 3000);
});
And this should be the order of actions: 这应该是操作的顺序:
You could trigger another function at the end of the timer. 您可以在计时器结束时触发另一个功能。 Since you only need to call it once.. You could just use setTimeout
由于您只需要调用一次即可。您可以使用setTimeout
document.getElementById('myBtn').addEventListener('mousedown', function (){
alert("Ey, release the button!")
setTimeout(fireMe, 3000);
});
function fireMe() {
// Boom
}
You might also want to add clearTimeout on mouseup event. 您可能还想在mouseup事件上添加clearTimeout 。
Do something like 做类似的事情
var timer;
document.getElementById('myBtn').addEventListener('mousedown', function (){
timer = setTimeout(function(){
alert("Ey, release the button!");
}, 3000);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.