我有一个从10秒到1秒的连续倒计时,我需要在宝贵的时刻执行一段代码。
例如:如果倒计时是2秒,我需要在这2秒的最后100毫秒内执行一段代码,但当倒计时再次是2秒时,它需要一次又一次地执行。
下面是我尝试过的代码:
// for testing this code with countdown on console go to
//https://www.xul.fr/ecmascript/settimeout.php
function miseEnAttente() {
// here I should wait 900 millisecond before i execute the code
setTimeout(fonctionAExecuter, 900); //On attend avant d'exécuter la fonction
//fonctionAExecuter();
}
function fonctionAExecuter() {
console.log('code executed now ');
}
var boucle;
boucle = setInterval(function() {
//boucle should work all the time and check the countdown if its 2 second or not
var compteur1 = parseInt(document.getElementById('bip').innerHTML, 10);
if (compteur1 === 2) {
// clearInterval(boucle);
// i tried the clearinterval but it work only once , when the countdown is 2 seconde again i will not execute
/** i tried to sleep the code here but its same result as settimeout
function setSleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function Display() {
console.log('Wait for 900 ms!');
await setSleep(900);
console.log('After 900 ms!');
}
Display();
fonctionAExecuter();
}
**/
}, 10)更清楚地说:
倒计时总是从10秒到1秒,然后回到10秒。如果倒计时是2秒,我需要执行一段代码,而不仅仅是一次。
发布于 2021-01-28 19:17:33
我认为这段代码可以满足您的需求。首先,我们使用setInterval每隔2秒运行一次,或者您需要的任何时间。在该代码中,我们为间隔运行的时间量创建了一个setTimeout。我放入了一些日志,以便能够检查数字。
const time = 2000
setInterval(() => {
const timer = setTimeout(() => {
clearTimeout(timer)
const date = new Date()
console.log(
`Fires in the last 100 milliseconds. M:S:MS = ${date.getMinutes()}:${date.getSeconds()}:${date.getMilliseconds()}`,
)
}, time - 100)
const date2 = new Date()
console.log(
`Main timer, fires every ${time} milliseconds. M:S:MS = ${date2.getMinutes()}:${date2.getSeconds()}:${date2.getMilliseconds()}`,
)
}, time)值得注意的是,javascript中的时间并不是100%可靠的,尤其是setTimeout和setInterval。如果您在setInterval中有一个长时间运行的任务,该任务花费计算机的时间比间隔时间长,则间隔中的下一次运行将不会在您所需的时间运行。
发布于 2021-01-28 19:30:21
与其使用两个超时或间隔,我会推荐一种不同的方式,有点像这样:
获取开始时间,这是milliseconds
下面是一个例子(只需点击'Run code snippet'):
let seconds;
let targetTime;
let difference;
let codeExecuted;
let myInterval;
function test() {
difference = targetTime - Date.now();
if (parseInt((difference) / 1000) != seconds) {
seconds = parseInt((difference) / 1000);
document.getElementById("myText").innerHTML += seconds + ".. "
}
if (!codeExecuted && difference <= 2100) {
document.getElementById("myText").innerHTML += "execute code "
codeExecuted = true;
}
if (difference <= 0) {
clearInterval(myInterval);
reset();
}
}
function reset() {
let currentTime = Date.now();
seconds = 10;
codeExecuted = false;
targetTime = currentTime + seconds * 1000
myInterval = setInterval(test, 20);
}
reset();<span id="myText"></span>
https://stackoverflow.com/questions/65935695
复制相似问题