What is the optimal method for verifying two distinct conditions simultaneously using Javascript?

Hey there, I'm working on a code snippet to check the status of a Rails model. Here's what I have so far:

var intervalCall = setInterval(function(){
  $.post("getstatus", {id:id});
  var finished = "<%= @sentence.finished%>";
     // CONDITION ONE: STOP INTERVAL WHEN THIS HAPPENS LATER
  if ("<%= @sentence.result %>"){
        clearInterval(intervalCall);
        state_2();
  }
     // CONDITION TWO: KEEP INTERVAL RUNNING AFTER THIS EARLIER EVENT
   else if (String(finished)== "true"){
        state_1();
    }
},3000);


intervalCall;

I'm looking for suggestions on how to better structure this flow. Any ideas?

Thanks in advance!

Answer №1

// The setInterval and setTimeout functions return the timer id
var intervalCall;
function updateStatus (){
    // When making a post request, a callback function is needed to process the data response from the server
    $.post("getstatus", {id:id}, function  ( data ) {
        data = $.parseJSON ( data ) // Assuming you are using jQuery and the data is in JSON format
        if ( data.result ){
            state_2(); // If you want to pass the result as an argument, use state_2( data.result )
            return;
        } else {
            // No need to use a finished flag, when there is a response with no result, call the function again after a delay
            // Any action you want to take when there is no successful result can be written here

            state_1();
            intervalCall = setTimeout ( updateStatus, 3000 );
        }
    });
}, 3000);
intervalCall = setTimeout ( updateStatus, 3000 );

Some updates have been made

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

Book Roulette: Your Next Random Read

I created a code for a random quote generator and now I want to create something similar, but with images this time. I am looking to add a feature on my page where it can recommend a book by displaying its cover image when a button is clicked. For the pre ...

Getting the ID of a select input option in Vue.js using FormulateInput

Recently, I've been working with a FormulateInput select component that looks like this: <FormulateInput name="broj_zns-a" @change="setZns" :value="brojZnsa" type="select" label="Broj ZNS- ...

Run code once the Firestore get method has completed its execution

Is it possible to execute code after the get method is finished in JavaScript, similar to how it can be done in Java (Android)? Below is an example of my code: mColRef.get().then(function(querySnapshot){ querySnapshot.forEach(function(doc) { ...

Popup window for Ajax pagination in CgridView

In my project, I am displaying a set of data in a pop-up window using cgridview. However, when I attempted to implement ajax pagination, it failed to work properly. To address this issue, I created a view called listInvoices that contains only the cgrid da ...

What causes the Element to be null in Vue.js?

Could someone please clarify why the console.log output is showing as null, and provide guidance on how to resolve this issue? <template v-for="day in getMonthLength()"> <td> <input :id="day" type=number :value=&qu ...

What could be causing the removal of style classes from my element after it is appended?

Could you please explain how it functions? I am attempting to append a div with content using innerHTML and it is working, but without any of the styling classes being applied. const element = document.createElement("div"); element.classList.add("col ...

Issue with loading glb file in three.js: The 'format' property is not compatible with this material

When loading a .glb file I created in Blender using three.js, I am encountering an error message three.module.js:7950 THREE.MeshStandardMaterial: 'format' is not a property of this material.. The rest of the content loads correctly. What does thi ...

Filtering a table with a customized set of strings and their specific order using pure JavaScript

Recently, I've been diving into APIs and managed to create a table using pure vanilla javascript along with a long list of sorting commands that can filter the table based on strings. My goal is to establish an object containing strings in a specific ...

How to use the v-model to round up a number in Vue.js

I need to round up a number in my input field: <b-form-input id="amount_input" type="number" v-model="Math.ceil(form.contract.reward_cents / 100)" :state="validate(form.contract.reward_cents)"/> ...

The MongoDB GridFS is refusing to accept the buffer being written

Hey everyone, I've been working on this issue for nearly a day now and can't seem to figure it out. I'm utilizing multer's inMemory flag to upload an image from my website. My approach involves writing the buffer received from multer to ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

What is the best way to package JS in a partial view from ASP.NET MVC4 when it is sent back through AJAX?

Currently utilizing the System.Web.Optimization framework for bundling and minifying JavaScript, along with @section Script{ } sections to organize all scripts at the bottom of the page. This includes jQuery resources. In one of my pages, there's an ...

Guide to dynamically setting SCSS $variables in JavaScript after retrieving them from local storage in a React application

In my current situation, I am retrieving color combinations in hash values from the database through an API call and then saving them in localStorage for future use. However, I am facing a challenge when trying to access this data from localStorage and uti ...

Steps to update the toolbar color of Mui DataGrid

Check out this unique custom Toolbar I created specifically for Mui dataGrid function CustomToolbar() { return ( <GridToolbarContainer> <GridToolbarColumnsButton /> <GridToolbarFilterButton /> <GridToolbarDensit ...

Vue.js 2 view failing to update after modifying data in Vuex state

Greetings, I am currently working on developing a table to monitor the validation status of multiple items. Below is the VueX store configuration: mutations: { ..., set_scaninfos: function (state, scaninfos) { Vue.set(state, 'scaninfos&a ...

Different approaches for expanding object.prototype while utilizing jQuery

Once upon a time, I made the mistake of trying to extend Object.prototype and ended up encountering errors in my jQuery file. After doing some research, I found out that extending Object.prototype is frowned upon in the JavaScript community due to potentia ...

Let's set up a new project using Create React App and Node Sass with Chokidar, following the 7-1

Seeking a solution: I am relatively new to using React and would like to incorporate SASS into my project without ejecting or configuring webpack. My goal is to have isolated stylesheets for components, as well as global stylesheets for layout purposes. It ...

Eliminate the jQuery AJAX timestamp from the URL parameters

Is there a way to eliminate the jQuery AJAX cache buster code (_=3452345235) from string URLs? While working on a global AJAX fail handler, I need to identify which URL failed. However, every time I locate the failed request's URL, the jQuery cache q ...

Having trouble transitioning from Curl to Axios in Node.js? Encountering issues when trying to make a curl request using the provided certificates, resulting in ECONNRESET or

I've been struggling to make a successful curl request in Axios (Node.js) without any luck. A typical working curl request I use (can't provide exact details as the API is private) is like this: curl --cacert server.pem --cert client.pem:123pas ...

How can we handle updating jQuery actions such as Drag And Drop when Ajax replaces multiple chunks of HTML?

After some trial and error, I have finally devised a method for refreshing certain parts of the screen using Ajax, Taconite, and jQuery within Django - resembling Ruby on Rails partials. While I was quite pleased with the results, it appears that the code ...