Create an on-screen alert when a specific time is reached

Asked

Viewed 20 times

1

I have the following function:

function time() {
  let today = new Date();
  today.setMinutes(today.getMinutes() + 30);
  let h = today.getHours().toString().padStart(2, '0');
  let m = today.getMinutes().toString().padStart(2, '0');
  let s = today.getSeconds().toString().padStart(2, '0');
  document.getElementById('1').innerHTML = `${h}:${m}:${s}`;
}

This function is triggered when I press a button. But it needed that when the time that is played in HTML (in case local time + 30 min) was the local time, it would issue a alert default or a pop up, with a message to the user.

1 answer

3


Simply calculate the difference (in milliseconds) between the current date and the date on which you want to issue the alert, passing this interval to the second argument of the setTimeout.

Since you already have the instance of the "future" date, you can do something like this:

function time() {
  let future = new Date();
  future.setMinutes(future.getMinutes() + 30);
  let h = future.getHours().toString().padStart(2, '0');
  let m = future.getMinutes().toString().padStart(2, '0');
  let s = future.getSeconds().toString().padStart(2, '0');
  document.getElementById('1').innerHTML = `${h}:${m}:${s}`;
  
  let interval = future.getTime() - Date.now();
  setTimeout(() => {
    alert('30 minutos se passaram.');
  }, interval);
}

Notice that I renamed today for future just to make it a little clearer. Note also that Date.now returns the timestamp current, in milliseconds.

It is worth remembering that if the user leaves the page, timeout will lose its effect.

  • Thank you, it worked perfectly. Could you tell me if it is possible to trigger an audible alert? Some library maybe?

  • 1

    @Riberox, if you have the audio file URL, you can use the native API Audio. He returns a HTMLAudioElement which has a method play that can be used to play the sound.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.