12dec1990
12dec1990

Reputation: 115

SetInterval method executes only once on an onclick event

I recently saw a youtube tutorial on how to create desktop notifications and I thought it would be a good idea to have it serve as a reminder. For eg, say I want a specific reminder to appear(as a desktop notification) every 30 mins. This reminder should only be triggered when the trigger button is clicked. The issue is, with the code I have below, the setinterval method only seems to execute once. It seems to work fine if I don't include the click event, but as soon as I add the click event, it fails to repeat. Any suggestions?

Here's a snippet of what I have:

<a href="#" id="trigger" onclick="notifyme()">Trigger</a>

    <script type="text/javascript">

        var myVar;          
        function showalert(){
                var notify;
                notify = new Notification('Reminder!',{
                        body:'How are you?'
                    });
                    window.location = '?message=' + this.tag;
                }
    function notifyme() {
      myVar = setInterval(showalert, 5000);
}

Upvotes: 1

Views: 331

Answers (1)

adeneo
adeneo

Reputation: 318182

It only works once because you redirect the browser with the line window.location = '?message=' + this.tag;, and when the page reloads, you have to click the anchor to start the interval again

<a href="#" id="trigger" onclick="notifyme()">Trigger</a>

<script type="text/javascript">
  var myVar;

  function showalert() {
    var notify;
    notify = new Notification('Reminder!', {
      body: 'How are you?'
    });

  }

  function notifyme() {
    myVar = setInterval(showalert, 5000);
}

Note that you generally have to ask for permission to show notifications

function showalert() {
  var notify;
  notify = new Notification('Reminder!', {
    body: 'How are you?'
  });
}

function notifyme() {
  if (Notification.permission === "granted") {
    var myVar = setInterval(showalert, 1000);
  } else {
    Notification.requestPermission(function(permission) {
      if (permission === "granted") {
        var myVar = setInterval(showalert, 1000);
      }
    });
  }
}
<a href="#" id="trigger" onclick="notifyme()">Trigger</a>

Upvotes: 1

Related Questions