The setInterval function will run just one time when triggered by an onclick event

After watching a YouTube tutorial on creating desktop notifications, I had an idea to use it as a reminder tool. For example, having a specific reminder appear as a desktop notification every 30 minutes when triggered by clicking a button. However, the code below only runs the setinterval method once when combined with the click event and fails to repeat. Any thoughts on how to fix this?

Here is a portion of the code in question:

<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);
}

Answer №1

When using the line

window.location = '?message=' + this.tag;
, the interval only works once because it requires clicking the anchor to start again once the page reloads.

<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);
}

It is important to note that permission is usually required to display 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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with reading response headers in AngularJS when using Apiary.IO?

I am attempting to mock my API using Apiary.io, but I am facing an issue where I cannot retrieve any headers from the response object in angularJS. I have verified that at least Content-Type: application/json is correctly set up by checking in firebug. The ...

How can we eliminate all elements from jQuery except for the first and second elements?

HTML <div class="geo_select"> <h3>header 3</h3> in Above HTML code i want to remove all element except <h3> and default content<div> inside the <div class='geo_select'> in jquery.. How to remove all ...

Instead of leaving an Enum value as undefined, using a NONE value provides a more explicit

I've noticed this pattern in code a few times and it's got me thinking. When you check for undefined in a typescript enum, it can lead to unexpected behavior like the example below. enum DoSomething { VALUE1, VALUE2, VALUE3, } f ...

Utilizing Vue.js to connect with a Node.js server

After setting up a basic Node.js server, the following code is running successfully: var http = require('http'); var server = http.createServer(); server.on('request', function(req, res) { res.writeHead(200, { 'content ...

Obtain the JSON response from the servlet

Is there a way to get a JSON response from a servlet in JavaScript? I am using AJAX post to send data to the servlet. Here is my AJAX code $.ajax({ type: "POST", url: "formDelegationServlet", data: { ...

Code is not running in ReactJS

My challenge is to use canvas and script to draw a rectangle with one diagonal line. However, when I try to do so, only the rectangle appears on my browser. It seems like the script is not being executed. Here's the code: import React, { Component } ...

implement a new directive in AngularJS that references another directive in HTML

Check out the Fiddle here Upon button click, a modal window appears. Inside this modal, there is a <template-placeholder></template-placeholder>. When the button is clicked, an if-check is performed to ensure it's the correct button. If ...

When defining a stripe in TypeScript using process.env.STRIPE_SECRET_KEY, an error of "string | undefined" is encountered

Every time I attempt to create a new stripe object, I encounter the error message "Argument of type 'string | undefined' is not assignable to parameter of type 'string'. Type 'undefined' is not assignable to type 'string& ...

Is there a performance benefit to using node.js over client-side JavaScript in comparison to Chrome/V8?

Currently, I am working on a client-side javascript application for image manipulation. However, some of the operations are running quite slowly in the browser, taking about 2-3 seconds to complete. To address this issue, I am considering implementing a s ...

Protractor: What is the best way to retrieve the baseUrl from the command line input?

How can I retrieve the baseUrl that was passed through the command line in Protractor? For example: protractor conf.js --baseUrl=http://myawesomesite.com I attempted to use browser.baseUrl to access the baseUrl set in my conf.js file, but it does not see ...

Problem with Azure Table JavaScript Solution

When attempting to utilize JavaScript to access Azure Storage Tables, I encountered an error that reads: "Error getting status from the table: TypeError: tableServiceClient.getTableClient is not a function." Despite finding multiple successful examples onl ...

What is the best way to transform an array of objects into a nested array through shuffling

I am dealing with a diverse array of objects, each structured in a specific way: data = [ { content: { ..., depth: 1 }, subContent: [] }, { content: { ..., depth: 2 ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

Multiple occurrences of setting the state on an array result in logging an empty array each

My current challenge involves fetching data from a backend server and storing it in an array. However, when I attempt to pass this array to another component, I encounter an issue where multiple empty arrays are being passed instead of one filled with data ...

Having difficulty ensuring DayJs is accessible for all Cypress tests

Currently embarking on a new Cypress project, I find myself dealing with an application heavily focused on calendars, requiring frequent manipulations of dates. I'm facing an issue where I need to make DayJs globally available throughout the entire p ...

Bidirectional Data Binding Using Meteor and React

When using Meteor, the getMeteorData() method is preferred over getInitialState(). But how can we achieve binding, especially with regards to a user's surname in their profile? ... getMeteorData() { return { u = Meteor.user() } }, componentRen ...

Having trouble retrieving the data associated with a specific ID from my datatable

I am looking to specifically load the UserData that belongs to the correct AdminId In this code snippet, all the UserData is loaded successfully. It's working fine. async mounted() { this.userData = (await DataService.index()).data; } Now, I wa ...

Unit test produced an unforeseen outcome when executing the function with the setTimeout() method

When manually testing this code in the browser's console, it performs as expected. The correct number of points is displayed with a one-second delay in the console. const defer = (func, ms) => { return function() { setTimeout(() => func.ca ...

What is the best way to modify the ID of a duplicated element?

I have been working on creating a drag and drop editor using react-smooth-dnd. The setup involves two containers: a toolbar with elements and an editor where the elements can be dragged and dropped. Each element in the toolbar has the following structure: ...

Exploring Nested Divs with Vue Test Utils

Recently, I came across this shallowMounted vue component: <div class="card p-relative"> <div class="card-header"> <div class="card-title h4"> a lovely title <!----> <!----> </div> </div ...