What is the best way to repeatedly execute my function at intervals using setInterval?

After attempting to run a for loop 10 times with setInterval to call my function again, I realized that my for loop only runs ten times. How can I fix this issue?

function randomThumbNews() {
        for(var i=0;i<10;i++){
        $.ajax({
            type: "get", url: "Home/Oku", data: {},
            success: function (data) {
                $("#thumbNews_" + i).html(data);
            }
        });
         }
    }
setInterval(randomThumbNews, 3000);

Answer №1

Consider trying this approach:

$.ajax({
    type: "get", 
    url: "Home/Read", 
    data: {},
    context: i, /* Remember that this value will be accessible as 'this' in your success callback */
    success: function (data) {
        $("#displayNews_" + this).html(data);
    }
});

Answer №2

The issue here is that when

function (data) {
     $("#thumbNews_" + i).html(data);
 }

is executed, the loop has already completed, so the value of i will always be 10.

Only one of your <div>s will display the results.

To resolve this, you can modify the function to prevent closure issues:

function ajaxAndSet(counter)
{
  $.ajax({
           type: "get", 
           url: "Home/Oku",
           data: {},
           success: function (data) 
           {
              $("#thumbNews_" + counter).html(data);
           }
        });
)

function randomThumbNews() 
{
   for(var i=0;i<10;i++)
   {
       ajaxAndSet(i);
   }
}

setInterval(randomThumbNews, 3000);

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

Gathering user information through Javascript to dynamically populate an HTML document

Looking to utilize JavaScript to extract the value entered in a search bar and then display it in HTML. function pullValue() { var search = document.getElementById("search-bar") } How can the extracted data be inserted into the following: <h3 class ...

What is the best way to streamline these two JavaScript lines and eliminate redundancy?

In order to address an issue, I implemented the following two lines of code: MyString = div.getAttribute('data-type') || div.getAttribute('data-id'); MyString = MyString.replace('RemoveThis', ''); Although the code ...

What is the best way to incorporate Vue.component with modules or Vue CLI?

I'm having trouble figuring out the correct way to declare a Vue.component within export default. This issue arises from following a tutorial on vuejs.org. https://i.sstatic.net/PH3VN.png Instead of using var app = new Vue, I am implementing it as ...

Python (Flask) hosts Angular project's main webpage file - index.html

Seeking guidance on serving an Angular single page application with Flask. I'm struggling to properly serve the default route, '/', that should load index.html and its associated components. Below is my Flask function: @app.route('/&a ...

What possible reasons could be causing the code to not run after my for loop?

<script> //grab all the input values when submit button is clicked const sub = document.getElementById("sub"); sub.addEventListener("click", (e) => { e.preventDefault(); //get input values var ...

Embed JavaScript code from an ASP.NET webpage into an HTML page on a separate domain

Is it possible to inject JavaScript code from an asp.net page into an HTML page on a different domain, such as http://www.codeproject.com/? How can I achieve this injection from my application? I am currently developing a plugin similar to Pinterest. When ...

How do I use Puppeteer to save the current page as a PDF?

Is it possible to convert a web page in a React project to PDF and download it upon clicking a button? ...

What method is used to initialize the variables in this JavaScript snippet, and what other inquiries are posed?

As a backend developer, I'm looking to understand this JavaScript snippet. While I grasp some parts and have added comments where I am clear, there are still sections that leave me with bold questions. function transformData (output) { // QUESTIO ...

Steps for choosing an image and embedding it within a div element

Upon loading the site, an image is displayed with the following code: <img id="some_Image" src="some_source"> However, I am looking to avoid requesting this image again from "some_source". This is because calculating the image can be resource-inten ...

Having no luck locating bower_components in the directory one level up

In my project, I have a directory structure that looks like this: /web /bower_components /bootstrap /jquery /typeahead.js /views /index.jade My goal is to utilize these components in my index.jade file using the following method: lin ...

Using AngularJS API within a standalone function: Tips and tricks

I'm diving into the world of AngularJS and I want to make an HTTP GET request to a distant server without messing up my current view code. After some research, I discovered a way to execute a function right after the HTML is loaded by using a standalo ...

The server appears to be up and running, however there seems to be an issue when attempting to access the API as it is returning an Error: connect ECONNREFUSED 127.0.0.1

Trying to decouple app and server. Successfully running, but encountering Error: connect ECONNREFUSED 127.0.0.1:3000 in Postman when hitting "app.get('/')" API despite making necessary changes. In ./routes/users.js const express = requ ...

How to sync two carousels in Bootstrap 5 to slide simultaneously with just one click on the next and previous buttons

I am trying to implement dual sliding carousels using Bootstrap 5, but I am encountering issues with getting them to slide simultaneously. Despite incorporating data-bs-target=".carousel", the synchronization isn't working as intended in my ...

Pagination handling on ASP.NET Core server-side operations

I am currently working on implementing server-side pagination for loading data progressively into the browser. Here is a snippet of my controller action code: [Route("api/meteorites")] [HttpGet] public IActionResult GetAll() { var meteorites = _co ...

Creating a fresh array by applying a filter and assigning keys

I am facing an issue with my array structure, it looks like this, [ [ "Show/Hide", "P000", "MAX-CT05 FVM2-", "S", 1532, -9.5929406005, null, null, ...

extracting array index from a Mongoose array

//index.js let countryNameList = { "name"=["Bangladesh","India","Australia"] } //Output Section let findCountryIndex = awaitDataModel.find({$indexOfArray:{CountryName:"Bangladesh"}}) console.log(findCountryIndex); //Expecting Output : 0 I am l ...

Is it possible to leverage the Next.js image component alongside canvas?

In my project, I am developing a scrollable image component inspired by the design of the Apple AirPods Pro website. To achieve this, I am utilizing images up to a size of 750 pixels for each iteration of the component. Currently, I am drawing these imag ...

Exploring the Big O complexity of QuickSort in JavaScript

My experience with QuickSort involved testing two algorithms on LeetCode for a specific problem. Surprisingly, both algorithms worked, but one outperformed the other significantly, leaving me puzzled about the reason behind the speed difference. One of th ...

Sending arrays to specific endpoints via ajax

I've implemented ajax to send data to a custom rest endpoint as part of creating a filter function on my WP site. However, I'm currently facing an issue with getting the tax_query to work with the array of terms collected on the front end using ...

Creating an object efficiently by defining a pattern

As a newcomer to Typescript (and Javascript), I've been experimenting with classes. My goal is to create an object that can be filled with similar entries while maintaining type safety in a concise manner. Here is the code snippet I came up with: le ...