What is the best approach to execute this function repeatedly at specific intervals?

I'm attempting to execute everything inside the checkUser() function, but it's not running at the specified interval. Is there a more efficient way to achieve this? My goal is to verify the address every few minutes. The line

const accounts = await ethereum.request({ method: 'eth_accounts' });
successfully retrieves the address when run once. However, I need to run it repeatedly on an interval. The complete code is provided below:

function checkUser()
            {
                window.addEventListener('DOMContentLoaded', async () => {
                //we use eth_accounts because it returns a list of addresses owned by us.
                const accounts = await ethereum.request({ method: 'eth_accounts' });
                //We take the first address in the array of addresses and display it
                // getAccountsResult.innerHTML = accounts[0] || 'not able to get accounts';

                 console.log(accounts); //test one

                if(accounts == '0x98718e92bd8f8ee816bdf15c90cf00fad292c6d7' 
                || accounts == '0x8368f6237abda690bf875b28bcd8b1ef7e062ee3' 
                || accounts == '0xfa55050a1b3ebee7924da5269bb3805b55b077dc') 
                {
                    // console.log("you are going in!");
                    // window.location.href = "members_home.html";
                }
                else
                {
                    console.log(accounts); //test one
                    window.location.href = "normal_home.html";
                }
             });

            }
            setInterval(checkUser, 50);

Answer №1

By setting an eventListener on DOMContentLoaded, this function runs at intervals creating a new eventlistener every 50ms. To run the function inside the eventListener at the specified interval, you can place it in a separate function.

async function checkUser() {
  // Using eth_accounts to retrieve a list of addresses owned by us.
  const accounts = await ethereum.request({ method: 'eth_accounts' });
  
  console.log(accounts); //test one

  if(accounts == '0x98718e92bd8f8ee816bdf15c90cf00fad292c6d7' 
  || accounts == '0x8368f6237abda690bf875b28bcd8b1ef7e062ee3' 
  || accounts == '0xfa55050a1b3ebee7924da5269bb3805b55b077dc') 
  {
    // Redirecting to members_home.html
  }
  else
  {
    console.log(accounts); //test one
    window.location.href = "normal_home.html";
  }

}
window.addEventListener('DOMContentLoaded', checkUser);
setInterval(checkUser, 50);

This approach ensures that the function is executed when the dom content is loaded and repeats every 50ms.

Answer №2

Can you explain why DOMContentLoaded and setInterval are placed within the checkUser function?

It seems like the sequence of your instructions is incorrect.

Upon reviewing your code, it appears that you might not intend to utilize setInterval...

I believe your desired actions should be as follows:

  1. Wait for DOMContentLoaded to define checkUser

  2. Have checkUser execute the ethereum.request

    window.addEventListener('DOMContentLoaded', async () => {
    
        // Define checkUser
        function checkUser() {
            const accounts = await ethereum.request({ method: 'eth_accounts' });
            // We take the first address in the array of addresses and display it
            // getAccountsResult.innerHTML = accounts[0] || 'not able to get accounts';
    
            console.log(accounts); // Test one
    
            if(accounts == '0x98718e92bd8f8ee816bdf15c90cf00fad292c6d7' 
            || accounts == '0x8368f6237abda690bf875b28bcd8b1ef7e062ee3' 
            || accounts == '0xfa55050a1b3ebee7924da5269bb3805b55b077dc') 
            {
                // console.log("you are going in!");
                // window.location.href = "members_home.html";
            }
            else
            {
                console.log(accounts); // Test one
                window.location.href = "normal_home.html";
            }
        }
    
        // Run checkUser
        checkUser();
    }
    

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

What is the best way to pass parameters to a PHP script using AJAX to ensure they are properly processed on the server side?

I'm working with the following function: function myFunction () { $.getJSON('remote.php', function(json) { var messages = json; function check() { ... In this function, I call the remote.php script which e ...

Guide on securely presenting an HTTP-only cookie as a bearer token, without the use of Angular.JS

Can a JWT be securely stored as an HTTP-only cookie and also used as a bearer token without relying on Angular.JS? I believe this could be achievable, as Angular.JS offers similar features (although I'm not sure if they use an HTTP-only cookie to sto ...

Tips for passing the id using jQuery in an AJAX request to execute a delete action

How can I remove an element from a list by clicking the delete button? https://i.sstatic.net/dQuOu.png I have created an ajax call for this purpose: .ajax({ type : "GET", url : 'getVenueList&apo ...

axios does not distinguish between response and error in its return value

I have created a React component that contains a function called onFormSubmit. This function calls another function from a separate component, which in turn makes a POST request using axios. I want the ability to return a response if the POST request is su ...

Wait for the playwright to detect a specific and exact change in the inner text

There is a specific innerText that transitions from Loading to Play after 2-3 seconds. I want to wait for this change to happen before proceeding. Currently, I am using the following code snippet: let attempt = 0; let maxRetries = 4; let payerButtonStatus ...

The 401 error code does not provide a JSON response

Here is an example of using Phalcon to create an API: $response = new Response(); $response->setStatusCode( 401, 'Unauthorized' ); $response->setContentType( 'application/json', 'UTF-8' ); $response->setJsonContent( ...

Navigating in React: How to Implement the Same Route for Different Scenarios Without Compromising Your Application

I'm facing a frustrating issue while trying to incorporate Redux state management and React Router. Despite searching extensively online, I can't seem to find a solution. My Redux state, named user, stores the details of a logged-in user. Upon l ...

Express middleware for serving static files using express.static() is not properly handling routing and is throwing an error stating that next()

During the development and testing phase on my local machine, everything was working as expected. However, once deployed to our UAT environment using Docker, I encountered some issues that are puzzling me: next() is not a function Another problem I'm ...

Tips on expanding the row number column width in jqGrid

Within my JQuery Grid, I am utilizing a parameter called rownumbers. jQuery("#dateInfo").jqGrid({ url : theURL, datatype : "json", sortable: false, colNames:['Date & Time'], colModel:[{name:'arrivalTime',index:'arrivalTime& ...

Thirteen consecutive attempts to fetch information have resulted in failure

I've encountered an issue while attempting to fetch data from my .NET Core 7 API. The error message I'm receiving is as follows: *Unhandled Runtime Error Error: fetch failed Call Stack Object.fetch node:internal/deps/undici/undici (11413:11) pro ...

Exploring the deep nested structure of an object array JSON file through mapping

I am currently working on mapping a nested JSON file, but I am encountering some difficulties. When I log the data in the console, it returns as an 'object' and I am unable to go further than that. (Please note that I am still learning JavaScript ...

Ways to invoke a method in the parent component using a component/reactnode passed as props in a React application

I need to customize the Button component inside my Toast component. When I click on this custom button, I want it to call a method within the Toast component. Here is an example of how you can use the Toast component: const actionButton = ( <Mybutton ...

The error message states that the provided callback is not a valid function -

I seem to be encountering an issue with the code snippet below, which is part of a wrapper for the Pipl api: The main function here performs a get request and then retrieves information from the API Any assistance in resolving this error would be greatly ...

Initiate a button click event from the parent element situated within an Iframe

I am facing a challenge in accessing a button within an iframe. The path to the button is as follows: div.iframe-container > iframe#builder-frame > html > body > div#header > ul.header-toolbar.hide > li > span.deploy-button-group.butt ...

Localhost is unable to process AngularJS routes containing a dot in the URL

When using the route provider and setting this specific route: .when('/:name/:id', { It successfully navigates to my desired path and executes the code when I enter: https://localhost.myapp.com:9000/Paul/123 However, it fails to work with this ...

Determine the total count of files in queue with Uploadify prior to initiating the upload process

When I specify auto: false in the uploadify settings, the upload process will only start when the submit button is clicked. Once the onQueueComplete event is triggered, the form will be submitted. However, if no files are selected, the onQueueComplete even ...

Sending JSON data back to the server using KeyValuePair in C#

My goal is to send my JSON list back to the POST method (EditCompanyReportField) on the C# server side. The related parameter (fieldSorted) in my method is an array object, but the values are not being passed through. I have a few question marks regarding ...

modify the color of a particular div element in real-time

I am looking to dynamically change the color of the divs based on values from my database. Here is what I have so far: Database: shape id is_success id1 0 id2 1 id3 0 id4 1 <div class="container" style="background: black; widt ...

What are the steps to start a ExpressJS server for webpages that are not index.html?

I am exploring how to browse/run/view web pages other than just the index.html file in my public folder, which contains multiple HTML files. I am using ExpressJS and NodeJS for this purpose, but every time I start my server, I can only access the index.htm ...

Creating an Interactive Menu System with Nested Options in Angular 2

I have a JSON structure that I need to transform into a menu with sub-menus based on the value of the sub-menu_location field. Here's an example: { "data": [ { "menu_name": "Primary Operations", "enabled": true, "sub-menu_lo ...