What is the reason for the clearInterval consistently functioning after the completion of the function?

Just starting out in web programming and currently delving into javascript and jquery ajax..

This snippet represents my javascript code. The refresh variable controls an interval for updating the chat by fetching chats from the database and displaying them in the chat container every 2 seconds. My goal is to stop this interval, append a new message to the container, then resume the interval after submitting the message.

The issue arises when I hit enter to submit the message - the new chat appears momentarily in the container but gets replaced as the container refreshes with records from the database (the clearInterval function doesn't seem to work yet). Interestingly, it only stops the interval once the function has completed. Why? Oh why? :(

var oldscrollHeight;
var newscrollHeight;
var refresh;
function refreshChats(){
  oldscrollHeight = $(".chatContainer").prop("scrollHeight");
  $.ajax({  
    url: "get_chats.php",  
    cache: false,  
    success: function(html){          
        $(".chatContainer").html(html);     

        //Auto-scroll             
        newscrollHeight = $(".chatContainer").prop("scrollHeight");  
        if(newscrollHeight > oldscrollHeight){  
            $(".chatContainer").prop({ scrollTop: $(".chatContainer").prop("scrollHeight") });
       }                 
    }  
  });  
}

$(document).ready(function(){

  refresh = setInterval(refreshChats,2000);

  $(".chatValue").keypress(function(e){
    if(e.keyCode == 13 && $(".chatValue").val() != ""){
        clearInterval(refresh);
        var me = $(".me").val();
        var chat = $(".chatValue").val();
        var time = $(".timeChat").val();
        $(".chatContainer").append(me + ": " + chat + " (" + time + ")"); //showing a new message before database updated
        $(".chatValue").val("");
        $.post("chat.php", {submitChat: true, chat: chat, time: time});
    } 
  });

});

Answer №1

It is assumed that the function refreshChats utilizes Ajax technology.

By clearing the interval, you effectively halt any further execution of the refreshChats function.

Even if an HTTP request has already been dispatched, it will not prevent the event handler from triggering once the response is received, allowing for processing to continue.

To prevent the processing of the response altogether, a flag must be set to cancel it or instruct the success handler to terminate without taking any significant actions.

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

Updating the organization of the models directory in Loopback

I am looking to update the structure of the models folder. As per the documentation, I can make changes to the json config file which is typically set up like this: { "_meta": { "sources": [ "loopback/common/models/**/*", "loopback/serve ...

Determine the horizontal movement of x and z on a flat surface while accounting for

Using HammerJS, I am able to manipulate a 3D object within an augmented reality environment. Everything functions properly unless I physically move my phone (which serves as the camera)... const newTranslation = new THREE.Vector3(this._initTranslation.x ...

capture the element with the specified #hash using Jquery

Illustration: Assuming I visit google.com/#search function checkHash(){ if(window.location.hash != hash) { $("elementhashed").animate( { backgroundColor: "#ff4500" }, 1 ).animate( { backgroundColor: "FFF" }, 1500 ); hash = window.location.hash; } t=se ...

Creating a quiz with just one question in React: A step-by-step guide

How can I add the functionality to handle correct and incorrect answers? I've designed a single-question quiz with multiple options. The Quiz component has been created. See the code snippet below: Quiz Component export default function Quiz(props) { ...

Error: The code has a syntax issue due to an unexpected "function" token while using

Recently, I decided to try out Node version 6.2.1 with some of my code. My goal was to migrate the hyper-callback oriented codes to a cleaner and potentially more efficient approach. Surprisingly, when I attempted to run the node code in the terminal, an ...

What is the process for generating a fresh instance of an Angular service?

Hey there, I've been pondering a solution to a little dilemma I'm facing. Let me share my thoughts and see if you can lend some insight or tell me where I might be going astray. Setting the Stage: In the realm of angular app creation, it's ...

Displaying outcomes in dialog box when button is pressed

I am working on a website where I want to enhance the user experience by displaying output in a dialogue box upon click. The current setup involves the user selecting a vendor and time duration, with the results appearing below the Submit button. However, ...

Grab the code snippet from JSFiddle

I apologize for the seemingly simple question, but I have been struggling with it. I tried looking at similar questions, but I couldn't find a solution. Despite copying the code from http://jsfiddle.net/sB49B/21/, I can't seem to get it to work ...

Utilizing Jquery and php for form validation

I'm currently working on a form that includes radio buttons and I am attempting to validate it using jq/$.ajax before submitting the information in php. form.php <tr> <td class="h"><span class="txt_wht">t1</span></td> ...

Identifying if a variable is redirecting

Dealing with React Router Dom V6 I am facing an issue with two loader functions that make server requests. async function fetchUserDetails(userId, userAction) { const token = getAuthToken(); const userData = await axios({ url: API.endpoint + &apos ...

Joomla page experiencing JSON encoding issue related to RokSprocket plugin

I have a Joomla plugin called RokSprocket that loads all my Joomla articles from a table. The issue I'm facing is that I have approximately 80 articles, and initially only 10 of them are shown upon loading with a button to load more. When I click the ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

Steps to create a clickable row with color change in Angular 4

How do I make an entire row clickable and change the row color when a checkbox is clicked? This is my HTML file: <section class="others"> <div class="sub-header">Others</div> <p class="text-center" *ngIf="otherTests.length === 0"> ...

The value 'true' was returned for an attribute 'exact' that is not of boolean type

How can I resolve this warning? Sample Code const Main = (header, navigation) => { return ( <> <div> {navigation !== false && <Navigation />} </div> </> ) } I attempted this soluti ...

Some PDF files appear as blank when shown using a Base64 encoded string

I am attempting to display a PDF file on a web page using its base64 encoding. Below is the ReactJS code I am using: <object style={{ width: '100%', height:'842pt' }} type="application/pdf" data={`data:application/pdf;base ...

How can I generate a dummy JSON response using Backbone Fetch?

Exploring Backbone and looking for a way to simulate the response of a .fetch() call within a model without using a testing library or connecting to an external service. If the setting in the model is this.options.mock === true, I'd like to use an in ...

Creating an ESNext JavaScript file and integrating it into an Angular 2 project: A comprehensive guide

I am facing an issue with my js file named UserService.js and source.js, which has been transformed using transformer typescript. My objective is to integrate this transformed js file into Angular. UserService.js import { Source } from "./source" ...

What is the best approach to unit testing this React Component?

I have created a component that acts as a wrapper for another component. My question is, how should I approach unit testing for this component? Besides checking the state and method calls to ensure they update the state correctly. Other than rendering pro ...

Guide to acquiring the webViewLink using Google Drive Api v3?

I'm having trouble locating the webViewLink. The documentation (https://developers.google.com/drive/api/v3/reference/files) states that I should receive this parameter when requesting gapi.client.drive.files.list(). However, I don't even have a c ...

Steps for adjusting the status of an interface key to required or optional in a dynamic manner

Imagine a scenario where there is a predefined type: interface Test { foo: number; bar?: { name: string; }; } const obj: Test; // The property 'bar' in the object 'obj' is currently optional Now consider a situatio ...