Utilizing setInterval() for straightforward and continuous polling operations

When developing a basic web application that requires periodic data updates for the user, is there any disadvantage to using setInterval() to fetch JSON from an endpoint instead of utilizing a more formal polling framework?

As an illustration, let's consider the scenario where I need to refresh the status of a processing job every 5 seconds.

Answer №1

To prevent any potential delays or function stacking, I recommend using the setTimeout method. This allows you to schedule a function to run after a specified delay and ensure that each request is handled efficiently.

Here's an example implementation:

function updateData() {
    // Perform Ajax call here, and then schedule a refresh:
    setTimeout(updateData, 5000);
    // Additional logic...
}

// Initial trigger for the function, or directly call updateData
setTimeout(updateData, 5000);

Answer №2

Implementing a basic non-blocking polling function in modern browsers can be achieved using Promises:

var wait = time => new Promise(resolve => setTimeout(resolve, time))
var pollFunction = (promiseFunc, time) => promiseFunc().then(
             wait(time).then(() => pollFunction(promiseFunc, time)))

// Print "Hello World!" every second
pollFunction(() => new Promise(() => console.log('Hello World!')), 1000)

Answer №3

Here is a simple way to achieve this:

let count = 0, limit = 50, speed = 100;

function iterate(){
    count += 1; 
    /* Your code goes here. Blah blah... */
    if (count === limit) clearInterval(timer);
}

let timer = setInterval(iterate, speed);

Answer №4

Although this question is from a while back, I came across it and wanted to share some alternative solutions to enhance it in the StackOverflow fashion. One approach you might want to consider is similar to the method described here, known as long polling. Another option is to use WebSockets, such as socket.io.

The first method involves sending a single AJAX request and waiting for a response before sending another one. On the backend, the response is only delivered once the status changes, allowing you to continuously monitor the status until it changes.

On the other hand, socket.io acts like jQuery for Websockets, enabling you to establish a socket connection with any browser to push real-time data without needing to constantly poll the server. This system is akin to Blackberry's instant notifications and is ideal for achieving immediate updates.

Answer №5

Make adjustments to @bschlueter's response, and remember, you have the ability to terminate this polling function by executing cancelCallback()

let cancelCallback = () => {};

var sleep = (interval) => {
  return new Promise((resolve) => {
    cancelCallback = () => {
      console.log("Canceling...");
      // send cancellation message...
      return resolve('Canceled');
    }
    setTimeout(() => {
      resolve("tick");
    }, interval)
  })
}

var poll = (promiseFunction, interval, timeout) => promiseFunction().then(() => {
  let snooze = async(interval) => {
    let result = await sleep(interval);
    // perform actions once sleep is completed
    console.log("Sleep has ended, do something...");
    return result;
  }


  // check if cancelCallback is an empty function,
  // if so, schedule a timeout to trigger cancelCallback()
  if (cancelCallback.toString() === "() => {}") {
    console.log("Setting timeout to execute cancelCallback()")
    setTimeout(() => {
      cancelCallback()
    }, timeout);
  }

  snooze(interval).then((result) => {
    // verify if sleep was canceled, if not, proceed with polling
    if (result !== 'Canceled') {
      poll(promiseFunction, interval);
    } else {
      console.log(result);
    }
  })

  // perform action1...
  console.log("Performing action1...");

})


poll(() => new Promise((resolve) => {
  console.log('Hello World!');
  resolve(); 
}), 3000, 10000);

// perform action2...
console.log("Performing action2....")

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

The width:auto attribute for images in ie6 is not functioning as expected

I am facing a challenge with dynamically changing and resizing an image element to fit its container. My current approach involves: Resetting the image: // Ensuring the 'load' event is re-triggered img.src = ""; // Resetting dimensions img. ...

Dynamically injecting Ace editor into an Angular 2 application

My goal is to dynamically load the ace editor into my angular2 application when a button is clicked. However, I keep encountering an error in the console that says: Error: ace.edit can't find div #editor Here's a snippet of the code I'm ...

What is the best method for creating a fade effect on a div background?

I am trying to animate a div with the id #test from a 0 opacity background to an opacity of 0.7 using CSS rgba values, but for some reason, the .animate function is not working as expected. Here is my CSS: #test { background-color: rgba(0, 0, 0, 0); ...

Avoid deleting a row in Sequelize if it is referenced in another association

Is there a method in Sequelize.js to trigger an exception when attempting to delete a row that is associated with another entity? For example, consider tables for Roles and Users. They have a many-to-many association, allowing any user to have multiple ro ...

The ID of the jQuery droppable element cannot be found

Is there a way to retrieve the ID of a li element from a droppable function? Currently, when I try to do so, it returns undefined. Any suggestions on why this might be happening? The structure of each li element is as follows: <li class="ui-state-def ...

Enhance user input with Struts 2 autocompletion feature

<ajax:autocompleter name="cityName" list="list" size="1" label="Select City" listValue="cityName" listKey="id" autoComplete="true"></ajax:autocompleter> I encountered an issue while implementing Struts 2 with AJAX, as the autocomplete fun ...

Ways to obtain data in JavaScript function from HTML

Struggling to pass the key from a database query in HTML using PHP to a JavaScript function? You're not alone. The challenge lies in passing the field_id to the updateRecords() JS function through the onClick() event of an HTML button. Previously, se ...

Testing Your Angular 7 Code: Unit Testing Made Easy

I am currently working on developing unit tests for this angular script: export class DataService { private csrfToken: string = ''; private isContentShown: BehaviorSubject<boolean> = new BehaviorSubject(true); constructor(private h ...

Injecting Vue.JS data into an HTML attribute

I'm currently exploring Vue.JS and working on a status bar. I am curious about how to incorporate data from Vue into an HTML attribute. <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="score" aria-valuem ...

Exploring the documentation of node.js with doxygen

When it comes to my C projects, I make sure to document them using Doxygen. Recently, I delved into the world of NodeJs and attempted to document .js files with Doxygen, but unfortunately, no output was generated. Despite my efforts to search for answers ...

Steps to clear a form after submitting it

Hello all, I have a rather complex form that sends a message successfully with an alert after submission. I'm wondering how I can clear the entire form once it has been submitted to make it simple? Below is my HTML Form and JavaScript code. I would l ...

Material-UI Masonry: Eliminate excess spacing on the right side

When utilizing Material-UI, I encountered an issue where the width of the Masonry Component does not completely fill the width of its parent container. The empty space left has a width exactly equal to the spacing between elements, which is understandable ...

Error: JSON data abruptly terminated (Node.js)

As a beginner developer diving into the world of API's, I've encountered a recurring error in Node.js that seems to be causing crashes: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymo ...

Leveraging Next.js ISR to pass extra information to the getStaticProps function from the getStaticPaths

Inside SingleBlogPost.jsx, the code for generating blog pages by their slug is as follows: export async function getStaticPaths() { const res = await fetch("http://localhost:1337/api/posts"); let { data } = await res.json(); const paths = data.map(( ...

An error occurred while trying to upload the image: Undefined property 'subscribe' cannot be read

Recently, I implemented a create post function that allows users to fill in the title, content, and upload an image. However, I encountered an issue where the progress bar fills up and the image gets uploaded to Firebase successfully, but it doesn't a ...

The data passed into the child component via Input() retains its original value even after being modified within the child

While passing an object containing data length and an array of objects to a child component, I noticed a strange behavior. Even after changing the data in the child component and reloading the page, the edited property still persists. To visualize this is ...

Why does the combination of "minus, space, minus" result in the "plus" operation?

When running the command 'node -e 'console.log(- -1)' it outputs 1, which is expected. However: When executing the command 'node -e 'console.log(1 - - 1)' it displays 2, which puzzles me. It seems like when subtracting a ne ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

Tips for encoding AngularJS ng-model in real-time

Recently, I embarked on a new project and wanted to incorporate some AngularJS magic. The only obstacle is my limited expertise in AngularJS or JavaScript, making it difficult for me to figure out how to make it work. One key requirement is that the functi ...

Integrating FlaskWTF with Vue frontend: sharing CSRF tokens securely

I'm currently developing an application that combines a Vue frontend with a Flask backend. While I am creating forms in Vue, I am looking to enhance security using FlaskWTF for CSRF/XSRF protection and form validation on the backend. To implement th ...