javascriptsetintervalsafari-push-notifications

How to run a Javascript alert every Friday at 16:00


Is this possible using setInterval()?

In the below example, the alert is every 5 seconds...

<script type="text/javascript">
  setInterval(function() {
    // alert("Message to alert every 5 seconds");
}, 5000);
</script>

I'm trying to run safari push notification inside the interval function, maybe it isn't the best practice, but it's a workaround for now

function Notifier() {}

    // Returns "true" if this browser supports notifications.
    Notifier.prototype.HasSupport = function() {
      if (window.webkitNotifications) {
        return true;
      } else {
        return false;
      }
    }

    // Request permission for this page to send notifications. If allowed,
    // calls function "cb" with true.
    Notifier.prototype.RequestPermission = function(cb) {
      window.webkitNotifications.requestPermission(function() {
        if (cb) { cb(window.webkitNotifications.checkPermission() == 0); }
      });
    }

    // Popup a notification with icon, title, and body. Returns false if
    // permission was not granted.
    Notifier.prototype.Notify = function(icon, title, body) {
      if (window.webkitNotifications.checkPermission() == 0) {
        var popup = window.webkitNotifications.createNotification(
        icon, title, body);
        popup.show();

        return true;
      }

      return false;
    }

    $(function() {
      var notifier = new Notifier();
      if (!notifier.HasSupport()) {
        $("#error").show();
        return;
      }

      $("#request-permission").click(function() {
        $("#error").hide();
        notifier.RequestPermission();
      });

      $(function() {
        if (!notifier.Notify("#", "MESSAGE")) {
          $("#error").text('Permission denied. Click "Request Permission" to give this domain access to send notifications to your desktop.');
          $("#error").show();
        } else {
          $("#error").hide();
        }
      });
    });

Solution

  • You can use something like:

    <script type="text/javascript">
        var date = new Date();
        console.log(date.getDay());
        console.log(date.getHours());
        if(date.getDay() === 6 && date.getHours() === 17) {
            console.log("HELLO WORLD!");
        }
    </script>
    

    getDay() returns the day of the week from 1 to 7 (friday would be a 5) and getHours() returns the hour from 1 to 24. You can continue from here :)

    Update: this checks the date every 5 seconds with setInterval() if that's what you need:

    <script type="text/javascript">
    
    function checkDate() {
        var date = new Date();
        console.log(date.getDay());
        console.log(date.getHours());
        if(date.getDay() === 6 && date.getHours() === 17) {
            console.log("HELLO WORLD!");
        }
    }
    
    var dateLoop = setInterval(function() {
        checkDate();
    },5000);
    </script>