The function is continuously executed using the setInterval method, each time with distinct parameters

Hey there, I have a question about a function that opens a chat form with different attributes when given an emp_id parameter. My goal is to have this form automatically refresh every 10 seconds. However, the current implementation is causing some issues. Whenever the emp_id parameter is changed, the chat messages and form are refreshed multiple times (double or triple), depending on how many times the emp_id is changed. Here is the JavaScript function in question:

function load_chat(emp_id) {
        var url = "#request.self#?fuseaction=objects2.popup_list_chatform"
        url = url + "&employee_id=" + emp_id;
        document.getElementById('form_div').style.display = 'block';                            AjaxPageLoad(url,'form_div',1,'Yükleniyor');
        setInterval( function() { 
            load_chat(emp_id); 
        },10000);
}

When clicking on a user from a list of names, this form is opened using the above function. The issue arises when switching to another user by changing the emp_id, as it causes both the previous and current forms to refresh unnecessarily. How can I modify this behavior so that only the last emp_id value refreshes, instead of all previously changed ids?

Thank you for your assistance, I really appreciate it!

Answer №1

This code snippet effectively encapsulates the process at hand. The timer id (tid) is enclosed within the function, ensuring that when load_chat is called, it will halt any running intervals.

After configuring the new URL, the interval timer will be initiated once more.

var ChatModule = (function() {
    var tid,
        url;

    function refresh()
    {
        AjaxPageLoad(url, 'form_div', 1, 'Loading');
    }

    return {
        load_chat: function(emp_id) {
            if (tid) {
                clearInterval(tid);
            }
            // set up URL
            url = "#request.self#?fuseaction=objects2.popup_list_chatform"
            url = url + "&employee_id=" + emp_id;
            document.getElementById('form_div').style.display = 'block';
            // loading ajax content
            refresh();
            // starting timer
            tid = setInterval(refresh, 10000);
        }
    }
}());

ChatModule.load_chat(123);

Answer №2

To ensure continuous execution of your function, consider using setTimeout instead. This way, each time the function is run, it will schedule the next execution based on a specified condition:

function execute_chat(emp_id) {
    ... // perform tasks
    if (condition_still_valid)
        setTimeout(function() { 
            execute_chat(emp_id); // with same id
        }, 10000);
}
execute_chat("x"); // initiate the process

Alternatively, you can utilize setInterval outside the main function and clear it as needed:

function get_chat_handler(emp_id) {
    return function() {
        ... // do something 
    };
}
var intervalID = setInterval(get_chat_handler("x"), 10000); // begin

// at a later point:
clearInterval(intervalID);

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

Attempting to employ the HTML5 file picker feature within the AppMaker platform

Hey there, I'm currently working on integrating the HTML5 file picker into my AppMaker app. (Since my app needs to run as the developer, I can't use Drive Picker). I've been able to display the file picker in an HTML widget using the follow ...

There was an issue with Angular 2.0 at :0:0, which was caused by a response with status: 0 from the URL: null

I am a beginner in Angular 2.0 and I am currently working on creating a sample application using @angular\cli. To serve the application on my local machine, I use the command ng serve --open, which opens it at localhost:4200. Now, I have developed a ...

What are the steps to create a function that behaves like instanceof when given a string as input

Is there a way to achieve something similar to this? var isChild = isInstanceOf( var1, 'Constructor') so that it is equivalent to var isChild = (var1 instanceof Constructor) The challenge is that the function Constructor is not available in t ...

Experimenting with event listener on an element using Jasmine

Within my class definition, I have this code: MyClass = function() { var view = { delegateEvents: function () { this.$el.on('click', 'input[type="radio"]', this.toggleServices); }, toggleServices ...

What is the reasoning behind assigning initial values to this function variable?

Upon logging arr early in this function, the displayed values are as follows. I initially anticipated it would display [[null,null],[null,null]]; however, it instead shows the value of arr once the function is completed. updateBounds() { let arr = [ ...

(IONIC) Issue with MomentJS locale functionality not functioning properly post-building process

I am currently utilizing the IONIC Framework and incorporating Moment.js for handling dates. I have set all strings to be in French using the code below: moment.locale('fr'); Interestingly, this works perfectly on the "serve" mode of Ionic. Ho ...

What is the best way to add a `<div>` before or after a specific `<p>` element based on the client's height?

I am facing an issue with inserting a div before a paragraph element based on the given clientHeight. Specifically, I need to locate the closest paragraph element from the specified clientHeight and then add a div before or after that particular element. ...

Encountered a glitch when attempting to retrieve a Redux state within an async function in Next.js 13

"activate customer" import SearchResultPage from "./resultSearchPage"; import axios from "axios"; import { useSelector } from "react-redux"; const fetchProduct = async () => { const response = await axios.get( ...

Is there a way to restrict the number of checkboxes selected based on the values of radio buttons?

I am currently working with a group of radio buttons: <input type="radio" name="attending_days" value="06-18-13"/>Tuesday June 18, 2013 <input type="radio" name="attending_days" value="06-18-13"/>Wednesday June 19, 2013 <input type="radio" ...

What is the best way to synchronize these two bootstrap sliders?

Looking to synchronize two Bootstrap 4 carousels? Check out the image below: https://i.sstatic.net/rAC3j.png I'm struggling to display the content of both carousels simultaneously with their respective indicators and arrow icons. Can anyone assist m ...

Toggle visibility based on the selected option from a drop-down menu

I have a dropdown menu, and once I select an option from it, I want that selection to automatically disappear. Since I am new to struts, I'm not sure how to achieve this. Can someone please provide some guidance? <td> <s:select he ...

The Angular web application utilizing an ASP.NET Web API that is hosted on AppHarbor is showing the incorrect webpage

Working on a web application using Angular and ASP.NET Web API in Visual Studio 2015 has been quite the journey for me. Upon running the solution in VS2015, I encountered two tabs opening in Chrome - one for my Angular client-side application and another ...

Problems encountered when attempting to create a link between two nodes on a force-directed graph using a mouse click

I'm currently working on creating an interactive graph where users can click on two nodes to establish a link between them (which can be removed later). My approach was inspired by Mike Bostock's example at: https://bl.ocks.org/mbostock/1095795 ...

Switching between states using JavaScript

Here is a code snippet I'm working with: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="C:\Users\rapandey\Documen ...

The process of extracting data from a form and storing it as global variables

Consider the following example: This is our HTML form <form action="test1" method="GET" name="frm"> First name: <input type="text" name="fname"><br> Last name: <input type="text" name="lname"><br> <i ...

Display only the requested view - CakePHP

I am looking to display the view independently, without including the <head> and other sections specified in the default.ctp file. The information I need to display is stored in an element: <?php echo $post['Post']['id']; ? ...

Troubleshooting Email Communication Errors: A Persistent Challenge

I am new to nodemailer and trying to work on a simple application. However, I keep encountering errors within the nodemailer module when running my app. Here is my app.js code: const nodemailer = require('nodemailer'); const transporter = node ...

What is the best way to conceal a specific class of DIV within a container, and how can I also hide another DIV within the same container by

I have a DIV class containing around 10 elements within a container. I am looking to implement a feature where these elements are hidden and shown one by one every 15 seconds using jQuery with a smooth fadeOut() effect. Your assistance in achieving this wo ...

Steps for displaying a post's image when hovering over its link in WordPress

One section of my website displays the latest 6 posts, and here is the HTML code for it: <div class="latest-posts"> <div id="latest-posts-title"> <p>Latest Posts</p> </div> <div id="latest-posts-pictures" ...

JSON - When an Object's Value Matches

Within my JSON file, I have an object that contains an array of nested objects. I am looking for a way to trigger a function based on the value of a specific object. If the value matches a certain number, I want to display only those objects within a desig ...