简体   繁体   中英

Why does the the alert box pop up every second on the minute in js

I am trying to make an alert box pop up on the hour. The minute it pops up, it pops up every second. Why is that so?

 function popup() { var today = new Date(); var currentMinute = today.getMinutes(); var currentHour = today.getHours(); if ( currentMinute == "00") { alert("another hour has passed. it is now hour " + currentHour + " of the day!"); } console.log( "popup" + currentMinute) ; } setInterval(function() { popup(); }, 1000);

The reason you get a popup every second is because you have used setInterval with an interval of 1000 milliseconds , which is 1 second. So your popup() function gets called every second. Once the time reaches an even hour (for example, 3:00:00), the value of currentMinute will be 00 for an entire minute , so when your function gets called again a second later (3:00:01), the if statement still evaluates to true and the popup gets displayed again. And again at 3:00:02, 3:00:03, etc until it is 3:01:00.

You could either change your interval to 1 minute ( 1000 * 60 ) so that it never gets called more than once on the same minute, or set some variable that records the hour when the popup was displayed and check that as well.

Here is an example of the first method:

 function popup() { var today = new Date(); var currentMinute = today.getMinutes(); var currentHour = today.getHours(); if (currentMinute === 0) { alert("another hour has passed. it is now hour " + currentHour + " of the day!"); } console.log("popup" + currentMinute); } setInterval(popup, 1000 * 60);

If you want the popup to occur in the first second of the hour you still need to check the time every second. If like @herohtar says you place a variable in the popup code you can restrict the popup to just once per hour.

Code below is based on your code, I've done minimal refactoring to keep it simple:

var hourOfLastPopup = -1;

function popup() {
  var today = new Date();
  var currentMinute = today.getMinutes();
  var currentHour = today.getHours();
    if ( currentMinute === 0 && hourOfLastPopup !== currentHour) {
      hourOfLastPopup = currentHour;
      alert("another hour has passed. it is now hour " + currentHour + " of the day!");
    }
    console.log( "popup" + currentMinute) ;           
}

setInterval(function() { popup(); }, 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM