Tips for looping with setTimeout even after a href redirect

Attempting to implement a looping method on a webpage (such as Facebook) like this:

function loopRefresh () {
  console.log("loop refresh method call");
  if (shallRefresh){
      setTimeout(function(){
        loopRefresh()
        //Do something here
      }, 5000);
  } else {
      setTimeout(function(){
        loopRefresh()
        //Do something different here
      }, 5000);
  }
}

Initially, everything seems to be functioning properly as the method is called every 5 seconds. However, an issue arises when the user clicks on the home button: https://i.sstatic.net/L7Bl8.png

This results in the page being reloaded due to the anchor tag and href, even though it doesn't lead to a new page, consequently interrupting the loop.

An onclick event has already been added to the Home Button calling this function:

function homeRefresh() {
  shallRefresh = true;
//setTimeout(function(){
//  Do the same thing here as in the true case in the loopRefresh method
// }, 2000);
}

The initial idea was to include the setTimeout call within this function so that the callback function would execute after the user clicked the button without involving the loopRefresh method. Unfortunately, attempting to pass the variable proved ineffective in resolving the issue.

Answer №1

It's important to remember to use event.preventDefault() at the start of your function, like this:

function refreshHomePage() {
  event.preventDefault(); // prevent default action here

  shouldRefresh = true;
  //setTimeout(function(){
  //  Do the same thing here as in the true case in the loopRefreshLayout method
  // }, 2000);
}

By using event.preventDefault(), you can stop the default hyperlink action from occurring.

Just a reminder: Once a page reloads, you won't be able to continue a JavaScript function.

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

Creating a New Entry in the Database with a Foreign Key Relationship Using Spring Boot REST API and JSON Payload via

all. I'm currently facing a challenge in tackling a straightforward issue. Within a Spring Boot application, I have two entities integrated with a web RESTful interface. While I can seamlessly insert and select rows that are standalone without depend ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Exploring the intricacies of XSS vulnerabilities

While researching XSS and how to prevent it, I have learned about the importance of input filtering, proper handling of application code, and output encoding in order to enhance the security of web applications. However, despite reading various articles on ...

Leveraging a Mongoose Schema Method within a Exported Mongoose Model

Lately, I've been developing an authentication system that is designed to either create a new user if no user with a specific ID exists OR retrieve a user with an existing ID. Through my exploration, I discovered that it's possible to determine w ...

Tips for retrieving selected items in an array object

Within my UI, I have a select field that, on change, populates corresponding data in a div with nested ul and li elements. What I am attempting to achieve is to convert the selected items within the list (which include checkboxes) into an object of arrays ...

Having trouble getting Google Tag Manager (GTM) to function properly on SharePoint?

I inserted the GTM code within the SharePoint Master Page body tag. <body> <--Body content goes here --> <!-- Google Tag Manager --> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXXXX" he ...

Replace Picture as you Scroll

Is it possible to swap images based on scroll position? For instance: When scrolling 100px, display img1.jpg When scrolling 200px, display img2.jpg When scrolling 300px, display img3.jpg Here's an example of what I'm looking for. Any suggest ...

Navigating the communication between a view component's form and a controller in ASP.NET Core

As a newcomer to web design using ASP.NET Core, I have created a view component that contains a form with various inputs related to a specific view model. One of these inputs happens to be a file input of the IFormFile datatype. My goal is to submit this ...

What is the most effective way to shorten a long URL while adding additional parameters?

Having a dilemma here. I am faced with a difficult situation regarding my URL - for example, www.mywebsite.com/first/second/something/index.html. What I would like to do is transform it into something along the lines of www.mywebsite.com/index.html?a=64& ...

What is the best way to retrieve text with xpath from an angular-based webpage?

Previously, google voice had a method to extract SMS codes using a "div" element. Recently, they made the switch to an ARIA-based framework with AngularJS. How can I now retrieve the string containing all my SMS codes from the webpage? Below is the comman ...

JavaScript file creation and opening issue in Firefox

Check out my code snippet below: var blob = new Blob([data], { type: 'text/plain' }); var downloadLink = angular.element('<a></a>'); downloadLink.attr('href', window.URL.createObjectURL(blob)); downloadLink.attr ...

What is the best way to activate an event using jQuery?

Currently, I am developing a web page where a modal window should open upon the user clicking on a specific radio button. To achieve this functionality through my jQuery code, I am trying to simulate the action of the user clicking on the radio button by: ...

Tips for forming JSON object within an array with the help of jQuery

Is there a way to generate JSON Objects using jQuery? I currently have a JSON Object in the following structure: { "1":{ "c_roleid":null, "ObjectID":1, "c_appname":"Default", "c_display":true, "c_add":null, ...

Creating an element in jQuery without the need for a closing tag

My situation requires dynamically building HTML elements using jQuery. Firstly, I initiate the process with the following function: function createSection(divName) { $("#"+ divName).append("<section id='team' class='pb-5'>&b ...

Use setTimeout and setInterval with the initial input without parentheses or double quotation marks

<!DOCTYPE HTML> <html> <head> <script type="text/javascript"> var count=0; function increaseCount(){ document.getElementById('txt').value=count; count++; setTimeout(increaseCount(),1000); } </script> </head&g ...

Tips for preventing redirection to the login page upon page refresh in a next.js application

I've been diving into user authentication and authorization using next.js. I managed to create a custom authguard hook that works well, except for one issue - when a user logs in and refreshes the page, they are redirected back to the login page. Aut ...

Unable to transfer information from Angular.js to Node.js

I am currently developing a MEAN stack application that combines AngularJS and Node.js. Here is a snippet of my AngularJS code: app.js: var app = angular.module('crudApp', ['ngRoute']); app.config(['$routeProvider' ...

Struggling with grasping the concept of Filtering Array in Eloquent Javascript Chapter 5?

Currently diving into the world of JavaScript through the enlightening pages of Eloquent JavaScript. Chapter 5 has been a breeze so far, except for one line of code inside a console.log statement that has me stumped: function filter(array, test) { ...

Reimagining the _id Attribute in MongoDB Using JavaScript Objects

In my Express project, I am conducting the following test: it('testing club', async () => { let club = await clubDAO.create(baseClubParams); console.log(club) const resp = await http.put(`/api/user/follow/${club._id}`); isO ...

Upcoming API and backend developments

When working with the NEXT project, API Routes provide the ability to create an API endpoint within a Next.js application. This can be achieved by creating a function in the pages/api directory following this format: // req = HTTP incoming message, res = H ...