Invoking JavaScript function at set intervals of time

I am currently working on JavaScript code where I am trying to establish a connection with a remote asp.net page (aspx) using AJAX. My goal is to check this connection for a maximum of 2 minutes, with intervals of 10 seconds each. Here is the logic that I have in mind:

If flag=true if seconds < 120 setInterval("GetFeed()", 2000);

Can anyone please assist me with this?

Below is the snippet of my code for checking the connection:

var learnerUniqueID1;
var flag='true';

function fnCheckConnectivity(coursId) 
{
    var url = 'http://<%=System.Web.HttpContext.Current.Request.UrlReferrer.Host+System.Web.HttpContext.Current.Request.ApplicationPath%>/TestConn.aspx'; 

    if (window.XMLHttpRequest) {
        learnerUniqueID1 = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        learnerUniqueID1 = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        alert("Your browser does not support XMLHTTP!");
    }
    learnerUniqueID1.open("POST", url, true);
    learnerUniqueID1.onreadystatechange = callbackZone;
    learnerUniqueID1.send(null);
}

function callbackZone() 
{
    if (learnerUniqueID1.readyState == 4) 
    {
        if (learnerUniqueID1.status == 200) 
        {
            parseMessageZone();
        }
        else
        {   
            flag='false';                       
            alert('We have detected a break in your web connection, \n please login again to continue with your session');
        }
    }
}

function parseMessageZone() 
{
    var result = learnerUniqueID1.responseText;
}        

function makePayment(obj)
{
    try
    {
        var Id = obj.attributes["rel"].value
        var res=confirm('Want to Continue.');
        if(res == true)
        {
            startRequest(Id);
        }
        else
        {
            return false;
        }
    }
    catch(Error)
    {

    }
}

function startRequest(Id)
{
    var milliseconds = 10000;
    currentDate = new Date();
    pollRequest(milliseconds, false, currentDate, 120000,Id);
}

function pollRequest(milliseconds, finshed, date, timeout,Id)
{
    if((new Date()).getTime() > date.getTime()+timeout)
    {
        return;
    }
    if(!finished){
          setTimeout(() => {
             if(//check backend to see if finished)     //which method will go here
             {   
                fnCheckConnectivity(coursId);
                 pollRequest(milliseconds, true, date, timeout,Id);
             }
             else{
                 pollRequest(milliseconds, false, date, timeout,Id)
             }
          }, milliseconds);
          return;
    }
}

Answer №1

It seems like you are looking to check the status of a request every ten seconds. Here is one way you could approach it:

function initiateRequest(){
    var interval = 10000;
    currentDate = new Date();
    timeout = 120000;
    
    initiatePolling(interval, false, currentDate, timeout);
}

function initiatePolling(interval, done, date, timeout){

    if((new Date()).getTime() > date.getTime()+timeout){
        // Timeout after 2 minutes
        return;
    }

    if(!done){
          setTimeout(function(){
             if(//check backend for completion){
                 initiatePolling(interval, true, date, timeout);
             }
             else{
                 initiatePolling(interval, false, date, timeout)
             }
          }, interval);
          return;
    }

    // Request has completed when reaching this point
}

Keep in mind that this function is recursive and may be subject to browser limitations on recursion depth. For the 2-minute timeout, you can handle it by setting it as an ajax prefilter or incorporating a variable incremented during each recursion.

Answer №2

It seems like you are looking to perform a task for 2 minutes every 10 seconds.

var interval = setInterval(function(){
// do the task
},10000); // execute every 10 seconds

setTimeout(function(){
clearInterval(interval);
},120000); // Stop the task after 2 minutes

Answer №3

Avoid having a script constantly running on your server or client system. Instead, consider utilizing tools like cron jobs for Linux or the task scheduler for Windows.

I provided you with an alternative approach rather than a definitive solution. Based on your needs, this tool appears to be the most suitable option.

Answer №4

Instead of relying on a push request where the client user must wait for a specified time before making a request, it is better to opt for a pull request method.

In this approach, an AJAX call can be initiated to the server, allowing the server to handle the request and potentially perform other tasks while waiting before sending back a response to the user once the data is ready.

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

Error Encountered When Loading the 'Oracle.DataAccess' File or Assembly

I encountered an error when running the application in asp.net. The error message reads: "Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. The located assembly's manifest definition does not match the assembly ...

What methods are available for managing model fields within a for loop in Django?

As a newcomer to Django, I am embarking on the journey of creating a Quiz web application that presents one question at a time. Upon selecting an answer using radio buttons, the application should promptly display whether the response is correct or incorre ...

What is the best way to navigate to a different page if the condition is false when using AJAX?

When adding a product to the cart through ajax, only logged-in users are able to do so. If a user is not logged in, they will be redirected to the login page. Below are the ajax requests in the blade template: $.ajaxSetup({ headers: { ...

Using Asynchronous JavaScript and XML (AJAX) to make calls to a web service

My program is showing an internal server error var parameters = "<?xml version='1.0' encoding='utf-8'?>" + "<soap:envelope xmlns:xsi='ttp://www.w3.org/2001/xmlschema-instance' xmlns:xsd='http://www.w3. ...

I'm puzzled as to why my get request seems to be hit-or-miss, working at times but returning a 404 not found error at other

Currently in the process of learning Angular and working on a project that involves a MongoDB database and Express for APIs. I am trying to retrieve comments for a specific post using the post ID. The GET request should return a list of comments, but the ...

Unable to reset HighCharts Speedometer value to zero

I am currently experimenting with implementing the highcharts speedometer. The goal is to simulate a connection meter - when there is a good connection, the meter should display values between 30 and 100. If the connection result from an Ajax call is any ...

What is the best way to define these variables at a global scope within my controller?

In my controller (NodeJS/Express), I have 10 routes that all use the same variables 'startDate' and 'endDate'. Is there a way to declare these globally so they don't need to be repeated in each route? Currently, my code checks if ...

Utilizing Typescript to filter a table and generate a transformed output for each item

What's the best way to return each mapped element of an array using an optimized approach like this: this.itemsList= res.map( ( x, index ) => { x.id = x.code; x.itemName = x.name; return x; }); I've tried optimizing it with a second me ...

Guide to setting variables in a Mailgun email template using Node.js

I have developed a Google Cloud Function that sends an email with variables obtained from another source. I am using mailgun.js and attempting to send the email using a pre-existing template in Mailgun. The challenge I'm facing is finding a way to rep ...

Analyzing JSON information and presenting findings within a table

Requesting user input to generate a JSON object based on their response. Interested in showcasing specific details from the object in a table format for user viewing. Questioning the efficiency and clarity of current approach. My current progress: In HTM ...

Is there a way to update the grid without causing a page refresh? Your advice

Currently, I am working on a grid system similar to that of a stock exchange application. The goal is to handle large volumes of data and have the page automatically refresh at set intervals without requiring a post back. What would be the most effective ...

Using Ajax and JQuery to show a success message prominently

Currently, I have a fully functional flash system implemented in PHP to display a success message to the user once an entry is created in the database. In one of the forms on my website, there is a select field where users should be able to seamlessly add ...

Having trouble understanding how to display an HTML file using Next.JS?

Currently, I am working on a project that involves utilizing Next.JS to develop a webpage. The main goal is to display a PDF file on the left side of the screen while integrating Chaindesk on the right side to create a chat bot capable of extracting inform ...

"Using the Google Maps directive inside a separate modal directive in Angular results in a blank map display

As a newcomer to Angular, I have encountered a hurdle while attempting to incorporate a 'google maps' directive inside another directive. The following code showcases a 'modal-view' directive that loads a form: angular.module(&apo ...

Why am I receiving a 404 error when trying to access an Angular 9 route within a subfolder

I am facing an issue with my Angular 9 app that is hosted in a domain subfolder. The problem lies in the index.html base tag, shown below: <base href="/subfolder/"> Everything works perfectly fine when the app is run locally without the ba ...

The X-UA-Compatible meta tag is not functioning correctly on an ASP.NET 4.0 website

In the process of developing an ASP.NET 4 application, I encountered the challenge of making it compatible with both IE8 and IE9. Despite trying various meta tags, none seemed to work as intended. I even looked into a forum discussion for assistance, but ...

Encountered an issue while working with the Wikipedia API

I have encountered an issue while using the Wikipedia API to retrieve data from Wikipedia. I am receiving an error and need assistance with resolving it. Below is the code snippet that I am using along with the error message: HttpWebRequest myRequest = ...

Exploring the compatibility between ADFS 2.0 and JSONP

My main website uses passive federation (ADFS 2.0) and includes javascript that communicates with an MVC Web API site using jsonp. I am facing a challenge in getting this WebAPI to support Single Sign On on the same machine but different port. The passive ...

Using Try and Catch effectively - tips and strategies

As I delve into learning JavaScript on my own, one topic that caught my attention is the try/catch structure. The tutorial I came across only covers how to implement it, but lacks in explaining its practical applications. Is there anyone who can shed som ...

I am having trouble successfully sending my object to the node server using the socket.emit() function in socket.io. What other functions can I use to transfer this data?

I have a Dot object that I need to send to the node server using socket.emit('add_dot_init', new Dot()). However, when the data is received by the server, it looks like this: { x: 15, y: 75, alp: 3.487639104390228 } My objective is for this dot ...