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

Manipulating Arrays in JavaScript: Techniques for Extracting Values Buried in Nested Objects

I am working with an array of objects that contain multiple "Book" objects with dynamic keys. My goal is to filter the objects in the array to only include those that have at least one new "Book" object. For example: const arr = [ { id: '123&ap ...

Animation event in CSS3 fails to trigger on Firefox browser

Exploring the potential of CSS3 animation to detect when an input transitions from the enable to disable state, I encountered a challenge specifically in Firefox. Here is the code snippet that showcases the issue: View Demo on jsFiddle HTML: <input t ...

Trouble arises when trying to insert a script tag into a live code editor using HTML

A few days ago, I successfully created a live code editor using the ace 1.2.9 library for my website guides. Now, I'm attempting to create a basic example, but when I try to enter text in the designated text area for the guides, the studio code compil ...

Guide on transforming Json information into the preferred layout and iterating through the loop

Currently, I am diving deep into the world of JSON and feeling a bit puzzled by data formats, arrays, objects, and strings. First things first, I'm in need of data structured like this (on a jQuery page). Would this be considered an object or an arra ...

Updating the state after receiving API results asynchronously following a function call

I am attempting to update the state asynchronously when my fetchWeather function is executed from my WeatherProvider component, which calls an axios request to a weather API. The result of this request should be mapped to a forecast variable within the fet ...

Storing the values of a React JS application in local storage using

Storing data received from the backend in local storage: async onSubmit(e){ e.preventDefault(); const {login, password } = this.state; const response = await api.post('/login', { login,password }); const user ...

Having trouble locating the objects in the parent scope of an Angular directive

My custom directive needs to access the object $scope.$parent.users. When I use console.log $scope.$parent: myDirective.directive('scheduleItem', function(){ return { restrict: 'EA', link: function($sco ...

Deactivating the ajax function is one of the key features of the Framework

I recently attempted to transition my app from plain HTML to framework 7, and while most things were running smoothly, I ran into a roadblock when it came to ajax requests. They simply wouldn't execute, resulting in an error message. Uncaught TypeErro ...

Creating Layouts with Bootstrap 3

I'm exploring the codepen below in an attempt to mimic the appearance of the image provided consistently across all screen sizes. However, there are two issues that I am encountering - firstly, the green numbers on the first line which represent the d ...

What steps can I take to resolve the issue of the "self signed certificate in certificate chain" error while trying to install plugins on VS Code?

After setting up VS Code on my Windows 7 x64 system, I encountered an issue when trying to install plugins - I kept receiving the error message "self signed certificate in certificate chain". Despite setting "http.proxyStrictSSL": false, I was still unable ...

Using Python, Scrapy, and Selenium to extract dynamically generated content from websites utilizing JavaScript

I am currently utilizing Python in combination with Selenium and Firefox to extract specific content from a website. The structure of the website's HTML is as follows: <html> <meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"> ...

Programmatically link an Angular JS model to a template using binding

When given an HTML template like the following: <div class="info"> <div class="title"><a href="property-detail.html">{{title}}</a></div> <div class="location">{{location}}</div> <div class="property ...

What is the best way to combine 2 javascript objects to create a JSON structure without any nested levels?

I am having an issue with my mock server setup. I am using npm faker to generate random data, and then trying to transfer that data to another JavaScript file. My goal is to have a JSON structure like the following: { 0: varOne: 'value' ...

Issue: mongoose.model is not a valid function

I've been diving into several MEAN tutorials, and I've hit a snag that none of them seem to address. I keep encountering this error message: Uncaught TypeError: mongoose.model is not a function Even after removing node_modules and reinstalling ...

Ways to retrieve the text of the chosen radio button label with the help of jQuery

There is a radio button on my webpage that looks like this: <div id="someId"> <label class="radio-inline"> <input name="x" type="radio" onchange="GetSelectedVal();">Yes</label> <label class="radio-inline"> ...

Is the `document.documentElement` consistently defined and always representing the HTML element?

I am looking to make changes to the <html> element using a script within the <head> section of an HTML page. My goal is to only access and modify the <html> element itself, without affecting any of its children. Should I wait for the DOM ...

What's preventing my Angular list from appearing?

I am currently developing an Angular project that integrates Web API and entity framework code first. One of the views in my project features a table at the bottom, which is supposed to load data from the database upon view loading. After setting breakpoin ...

Schema-specific conditions for JSON data

I have been experimenting with the if-then-else statement in JSON, but I am encountering some issues with it. { "type": "object", "minProperties": 2, "maxProperties": 2, "properties": { "human": { "enum": [ "Kids", "Ad ...

The next-routes server.js encounters an issue: TypeError - the getRequestHandler function is not defined within the routes

I encountered an issue in my server.js file. Here is the code snippet causing the problem: const { createServer } = require('http'); const next = require('next'); const routes = require('./routes'); const app = next ({ dev: ...

Implement scroll bar functionality on canvas following the initial loading phase

I am currently working with canvas and I need to implement a scroll bar only when it is necessary. Initially, when the page loads, there isn't enough content to require a scroll bar. My project involves creating a binary search tree visualizer where u ...