Ajax long-polling - Timeout triggering unexpectedly

I am having an issue with my Ajax code polling my IIS/ASP server. After calling msgPoll("") once, the function seems to be invoked repeatedly instead of every 30 seconds. Can you help me identify what mistake I might be making?

var msgTimOut;
function msgPoll(text) {
    var msgData = {};
    msgData.UID = $("#hidUID").val();
    msgData.data = text;
    $.ajax({
        type: "POST",
        url: "WSWebJudge.asmx/MsgPoll",
        cache: false,
        data: JSON.stringify(msgData),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {
            resp=JSON.parse(data.d);
            if (resp.status == 1) setMsg(resp.msg);
            if (msgTimOut) clearTimeout(msgTimOut);
            msgTimOut = setTimeout(msgPoll(""), 3000);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Messaging - textStatus: " + textStatus + " errorThrown: " + errorThrown);
        }
    });
}       

Answer №1

setTimeout(function(){msgPoll("")}, 30000)

  1. Your time limit has been reduced to just 3 seconds instead of the original 30 seconds
  2. Make sure to enclose the call within a function block - check out this link for more information on this topic.

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

Javascript: Anticipating a Return from an Argument

I am currently working on a function that requires an attribute to respond before proceeding with its process. The function call is structured like this : processResult(getResult()); The issue lies in the fact that the getResult function takes some time ...

Is it possible to extract the image name from AngularJS and then integrate it into a Laravel blade template?

I encountered a challenge when trying to integrate Laravel blade with AngularJS. Both frameworks use the same markup for displaying variables, so I modified the AngularJS variable like this: $interpolateProvider.startSymbol('<%'); $ ...

Retrieve the $scope object within an isolated directive

Is there a way to modify a $scope variable from within an isolated directive? I've experimented with the '@, =, &' syntax in the directive scope but haven't been successful. Here's a simplified version of my code: JS app.co ...

React useEffect only retrieves the last element of an array object

I am facing an issue where React seems to only save the last element in my array. Even though I have two elements, when mapping over them, only the last element is being placed in the hook each time. React.useEffect(() => { if (bearbeiten) { handleCli ...

Explore the input from multiple users to uncover the word that appears most frequently among them

Hey there (brand new to JavaScript), I am working on a simple program that requires input from multiple users through prompt pop-ups. For example: <script type="text/javascript> var userInput = prompt("Enter your input:"); </script> It&ap ...

using outlines for FontAwesome icons in React Native

I am struggling to use the fontAwesome + icon in the middle of a circle as one item. I have tried placing it inside a circle icon, but it doesn't seem to work properly. import IconFA from 'react-native-vector-icons/FontAwesome'; < ...

Datepicker malfunction in Django's administrative interface

Currently, I am attempting to filter results by dates using daterangefilter. However, I am experiencing issues with my datepicker functionality. Although the icon appears, the datepicker itself is not functioning as expected. In an effort to troubleshoot ...

How is it possible to encounter a Javascript unexpected token ] error within an HTML code?

While working on my project, I encountered a JavaScript error in the console of Chrome. The error message stated "Unexpected token ]" and it was pointing to a specific line of raw HTML code. I am puzzled about what could be causing this issue. Unfortunatel ...

Clicking on a checkbox and subsequently removing validation through jquery

Situation : When the 'I am Fresher' checkbox is selected, I want to hide the 'Experience field', but still keep its validation visible so that my form cannot be submitted. My Requirement : When the 'I am fresher' checkbox is ...

Assistance Needed with AJAX Requests for Navigating to Previous or Next Page

How can I implement AJAX to retrieve the Next/Previous Page(s) content? To make a call in a browser: page.php?page=1-1 or page.php?page=1 The response will be in plain text format. The pages should be loaded in either of these formats: 1-1 or 1 How ...

Node.js/Express - unable to retrieve client body data on server

I am able to retrieve data from express but I am facing issues when trying to post data to express... client: <html> <button onclick="myFunction()">send</button> <script> const data = {"experience" : 0}; ...

Using ajax to dynamically retrieve radiobutton values

When dealing with multiple radio buttons of the same name called "iva", around 8 in total, how can I use ajax to transfer the value selected if it's different from the default option? <td>IVA > Exento <input type="radio" name="iva" id="iv ...

What are the different ways to utilize request.profile in a Node.js environment?

I recently stumbled upon a code snippet that utilizes req.profile to read data. How is this even possible? const listNewsFeed = async (req, res) => { let following = req.profile.following following.push(req.profile._id) try{ let posts = await ...

Retrieving the output of JavaScript code in C#

How can I retrieve the value from a window.prompt() alert box in my C# Code Behind file? I know it's a simple line of JavaScript, but I want to execute it and get the result within my Code Behind. Whether it's done through a <script> tag in ...

Switch the array's value if the key is a match?

I'm currently facing an issue where my code does not push the object when the key matches. How can I update the value of the key instead when there is a match? this.state.data.concat(items).filter(function (a) { return !this[a.key] && (th ...

Obtain a listing of values that appear multiple times within an array

I need a solution to find values that appear more than once in an array. The current code I have is quite complex. var arr = [1, 2, 3, 4, 2, 3]; var flag = {} var exist2arr = []; for(var i = 0; i < arr.length; i++){ for(var j = 0 ; j < arr.leng ...

Adding the class ui-corner-bottom to the initial item in a list using JQuery Mobile

After experimenting with JQuery Mobile, I've had some success but now I'm facing a new issue. The first line of my list is automatically adding 'ui-corner-bottom' to the class, which gives the first item in the list bottom corners. Any ...

FireFox is unresponsive to OPTIONS requests

I have a webpage that is accessed through HTTP. The client-side code is making AJAX requests for authorization to the same domain, but using HTTPS, which causes CORS issues. When using FireFox, the request looks like this: // domains and cookies are chang ...

Activate colorbox once the content has been loaded through ajax into a concealed div

How can I trigger colorbox after ajax has loaded content into a hidden div? $('#recipe').on('keyup', function( event ){ if(this.value.length == 3) { /* Perform an ajax call, output the result to div #check-drink */ ...

What is the reason for the filter not displaying the IFRAME?

I have a filter set up to automatically embed YouTube videos for user-generated content by searching for links and verifying if they are valid YouTube videos. If they are, the video should be embedded using standard iframe code; otherwise, it remains just ...