What causes the initial AJAX response to be delayed by 10 seconds when using setInterval()?

I have a task that requires me to send an ajax request to display an image that changes every 10 seconds. However, I'm encountering an issue where my webpage remains blank for the first 10 seconds and only displays the first image after the initial delay.

var images = [
{ uri:'photo-1539154444419-e31272d30a31.jpg', description:'medium-coated black-and-white dog near grass during daytime' },
{ uri:'photo-1553882809-a4f57e59501d.jpg',    description:'black and tan Belgian dog' },
{ uri:'photo-1554196721-b507d7e86ee9.jpg',    description:'gray dog standing on grass' },
{ uri:'photo-1555661059-7e755c1c3c1d.jpg',    description:'black dog behind plants' },
{ uri:'photo-1555991415-1b04a71f18c5.jpg',    description:'adult white Samoyed beside man and woman' },
{ uri:'photo-1558121591-b684092bb548.jpg',    description:'white and black dog lying on sofa' },
{ uri:'photo-1559440165-065646588e9a.jpg',    description:'person holding dog leash short-coat black and white dog' },
{ uri:'photo-1560160643-7c9c6cb07a8b.jpg',    description:'short-coated brown and white dog' 
},
{ uri:'photo-1562220058-1a0a019ab606.jpg',    description:'pet dog laying on sofa' },
{ uri:'photo-1565194481104-39d1ee1b8bcc.jpg', description:'short-coated gray dog' }
];

var k = 0;
router.get('/images.json', function(req, res, next) {
res.send(images[k]);
k++;
if (k == 10){
k=0;
}
});

In HTML:

<!DOCTYPE HTML>
<html>
<head>
    <title>gallery.html</title>
</head>
<body>
    <img id ="image"<img src="data:," alt>
    <p id ="imagePara"></p>
    <script>
setInterval(function () {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState ==4 && this.status == 200){
    var json = this.responseText;
    var jsonObj = JSON.parse(json);

     var desc = JSON.stringify(jsonObj.description);
     var uriImage = JSON.stringify(jsonObj.uri);
     var uriImage2 = uriImage.substring(1, uriImage.length-1);

    var thisImage = document.getElementById("image");
    thisImage.src = "images/doggos/"+uriImage2;
    thisImage.alt = desc;

    var para = document.getElementById("imagePara");
    para.innerHTML = desc;
}
};
xhttp.open("GET","/images.json",true);
xhttp.send();
}, 10000);     
</script>
</body>
</html>

Seeking assistance with this issue. Thank you!

Answer №1

setInterval function doesn't execute the passed function immediately. The first call will occur after the initial duration has passed, and then continue to repeat based on the specified interval. For instance, if you have setInterval(fn, 10000), it will call fn after 10 seconds, then 20 seconds, and so on.

To ensure the function is called immediately, create a separate function, invoke it, and also pass it to setInterval like:

const fn = () => {
  // code goes here
};
setInterval(fn, 10000);
fn();

Your code snippet should be modified as follows:

const fn = () => {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var json = this.responseText;
      var jsonObj = JSON.parse(json);

      var desc = JSON.stringify(jsonObj.description);
      var uriImage = JSON.stringify(jsonObj.uri);
      var uriImage2 = uriImage.substring(1, uriImage.length - 1);

      var thisImage = document.getElementById("image");
      thisImage.src = "images/doggos/" + uriImage2;
      thisImage.alt = desc;

      var para = document.getElementById("imagePara");
      para.innerHTML = desc;
    }
  };
  xhttp.open("GET", "/images.json", true);
  xhttp.send();
};
setInterval(fn, 10000);
fn();

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

ES6 Set enables the storage of multiple occurrences of arrays and objects within

Review the script below. I'm currently testing it on Chrome. /*create a new set*/ var items = new Set() /*add an array by declaring its type as an array*/ var arr = [1,2,3,4]; items.add(arr); /*display items*/ console.log(items); // Set {[1, 2, 3, ...

How to place a stylish font over an image and recreate hover effects

I am looking to place social media icons below an image next to the photo's title, including Facebook, Twitter, Soundcloud, and Instagram. I want these icons to rotate along with the image when it is hovered over. HTML <div class="polaroid-image ...

How can I retrieve information from PHP using json_encode and access it in JavaScript?

Currently in the process of developing a web app using Phonegap and XUI. Fetching data from an external domain through an http request with XUI. The retrieval process is successful, as I am able to receive JSON data in the following format: ({"first":"J ...

Enhance User Experience with the Tooltip Feature and Customized

Here is the jQuery code I am using to style my tooltips: $(function() { // select all input fields within #tooltips and attach tooltips to them $("#tooltips :input").tooltip({ // place tooltip on the right edge position: "cen ...

The PHP script invoked by ajax is unable to run the start_session() function

When I run script A, it starts the session and initializes some variables. Afterwards, the script triggers an ajax call that calls script B: $("#galleryContent").load("B.php", {op : 'get_thumbs' }, ...

React - the constructor binding issue with 'this' keyword

I am a beginner in React and I am learning through creating a simple test application. However, I am facing an issue with "this" binding. I set up this app package yesterday using "create-react-app", so all the necessary plugins including babel should be u ...

Setting null for HttpParams during the call

I am encountering an issue with HttpParams and HttpHeaders after upgrading my project from Angular 7 to Angular 8. The problem arises when I make a call to the API, as the parameters are not being added. Any assistance in resolving this matter would be gre ...

Updating Select Options Disabled/Enabled in Angular 2

In my Angular2 project, I have 2 select elements: <div ng-controller="ExampleController"> <form name="myForm"> <label for="companySelect"> Company: </label> <select name="companySelect" id= ...

What are the steps to set up Apify webhooks?

Looking for assistance with setting up an Apify webhook. It's taking some time to finish a task, and I'm interested in adding an Apify webhook to trigger another task. However, I'm unsure of the steps needed to accomplish this. $.ajax({ u ...

Unable to access the newly created object's properties following the instantiation of a new resource in AngularJS

Currently, I am in the process of developing a new Resource utilizing AngularJS that falls under the category of Person. After successfully creating this resource, my goal is to retrieve the id associated with the new resource from the server. it('sh ...

How can I modify an array in Couchbase by using an N1QL query?

{ "name":"sara", "emailId":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="abcde8e2ea9627225c4b9a3afa7bbcc808cb554a1adaf">[email protected]</a>", "subjects" : [{ "name":"Math", "tutor":"alice", "classes" ...

Are there any pre-existing pop-up methods available for AngularJS?

Is there a way to create a simple pop-up window with static text and just one "Ok" button? In Java/Swing, it's possible to achieve this with just one line of code using pre-defined classes. However, when it comes to Angular pop-ups, it seems like the ...

Console log is not displaying the JSON output

I am currently working on implementing a notification button feature for inactive articles on my blog. I want to ensure that the admin does not have to reload the page to see any new submitted inactive articles. To achieve this, I am looking to use Ajax, a ...

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

Creating a CSS circle spinner with a half moon shape is an innovative way to add a unique touch

Image: Circular spinner rotating along the border rim of other solid circle For more details, please visit: https://codepen.io/sadashivjp/pen/oqqzwg I have created a UI codepen here and welcome any modifications or solutions. The code snippet is provided ...

Is there a way to set an antd checkbox as checked even when its value is falsy within an antd formItem?

I'm currently looking to "invert" the behavior of the antd checkbox component. I am seeking to have the checkbox unchecked when the value/initialValue of the antD formItem is false. Below is my existing code: <FormItem label="Include skills list ...

Prompting Javascript Alert prior to redirection in ASP.NET

My current code is set up to display a message in an update panel while updating: string jv = "alert('Time OutAlert');"; ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "msg", jv, true); It's working well in displaying the me ...

Verify if a fresh message has been added using AJAX

Is it possible to create a notification system similar to Facebook, where the tab title displays the number of new messages without refreshing the entire page? Below is a snippet of code from my website's message box feature that I am working on. < ...

What is the process for triggering events when the previous and next buttons are clicked?

Within the jQuery fullcalendar, there are previous and next buttons. Is there a way to trigger specific events when these buttons are clicked? ...

Trouble integrating jQuery post with PHP's $_POST method

I have a form that triggers an onkeyup event. My goal is to send a variable to my php script and display the result in a div. With help from this forum, I managed to partially get my test function working: jQuery.post(the_ajax_script.ajaxurl, When I use ...