execute a code in the last 100 millisecond of a countdown

I have a countdown running continuously from 10 to 1 second and I need to execute a code in a precious moment.

Example: if the countdown is 2 seconds, I need to execute a code in the last 100 milliseconds of the 2 seconds, but when the countdown is again 2 seconds it needs to be executed again and again.

Here is the code I tried:

// 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)

To be more clear:

The countdown is always running from 10 to 1 second and then it go back to 10.
I need to execute a code if the countdown is 2 second for ever not only once.

61 thoughts on “execute a code in the last 100 millisecond of a countdown”

Leave a Comment