1

im a noob in js xd, i want to put a text in an html in a choosen time of a clock! i want it to print "make a wish" when its 11:11 the code:

function startTime() {
    const today = new Date();
    let h = today.getHours();
    let m = today.getMinutes();
    let s = today.getSeconds();
    m = checkTime(m);
    s = checkTime(s);
    document.getElementById('txt').innerHTML =  h + ":" + m + ":" + s;
    setTimeout(startTime, 1000);
  }
  
  function checkTime(i) {
    if (i < 10) {i = "0" + i};  // add zero in front of numbers < 10
    return i;
  }

3 Answers3

0

This can be done via setInterval in javascript with some basic if condition checks.

First create a date object via new Date() then get hours and minutes, check if the hour and minute is equal to your specified time then print the value.

We need to set an interval of 60 seconds which is equal to 60,000 milliseconds to not print again the same value in that minute.

You can try this -

    setInterval(function(){ 
       var date = new Date(); 
       if(date.getHours() === 11 && date.getMinutes() === 11){ 
          console.log("make a wish");
       }
    }, 60000);
ved sinha
  • 1
  • 1
0

Something like this will do.

function startTime() {
  const today = new Date();
  let h = today.getHours();
  let m = today.getMinutes();
  let s = today.getSeconds();
  m = checkTime(m);
  s = checkTime(s);
  document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
  if (h == 11 && m == 11) {
    console.log("Make a wish");
  } else {
    setTimeout(startTime, 1000);
  }
}

function checkTime(i) {
  if (i < 10) { i = "0" + i };  // add zero in front of numbers < 10
  return i;
}
startTime();
<p id="txt"></p>
Nitheesh
  • 19,238
  • 3
  • 22
  • 49
0

Use the callback function from SetInterval and get currentt time. afterwards you can check if it 11:11. If successful dont forget to clear the intervall.

const innterval = setInterval(function () {
  check()
}, 5000);

function check() {
  var today = new Date();
  var t1111 = today.getHours() + ':' + today.getMinutes();
  if (t1111 === '11:11') {
    alert('11:11')
    document.getElementById('txt').innerHTML = t111 + ' PARTY!'
    clearInterval(innterval);
  }
  console.log('Current time: ' + t1111 + ' still Waiting')
}
<div id="txt"></div>
Maik Lowrey
  • 15,957
  • 6
  • 40
  • 79