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

Unable to utilize the "let" keyword in WebStorm

Currently, I am delving into learning typescript and attempting to create a simple 'let' statement. However, I encountered an error indicating the need to use ECMAScript 6 or later versions. The exact message from the typescript compiler states: ...

Capture a fragment of a scene and convert it into a unique texture using THREE.JS

I'm interested in creating a texture of a specific area in my scene, similar to the example shown in the official documentation for three.js framebuffer here. As I examine the code provided, there's one particular aspect that's unclear to me ...

Change the CSS element if the current URL is not example.com/page1 or example.com/page2

When I apply the following JS code snippets, my output is incorrect or does not display at all. Below are the codes in question: if (location.href != "website.com/page1" || "website.com/page2") { element.style.backgroundColor='none'; ...

How can we trigger the Skill bar effect upon scrolling to the section?

I have created a stunning Skill Bar that is functioning perfectly. However, I am looking to enhance the experience by having the skill bar effect trigger only when I scroll to that specific section. For example, as I navigate from the introduction section ...

"Incorporating Node.js (crypto) to create a 32-byte SHA256 hash can prevent the occurrence of a bad key size error triggered by tweetnacl.js. Learn how to efficiently

Utilizing the crypto module within node.js, I am creating a SHA256 hash as shown below: const key = crypto.createHmac('sha256', data).digest('hex'); However, when passing this key to tweetnacl's secretbox, an error of bad key siz ...

Angular directive does not focus on the text box

I've been working on creating text boxes using a directive and I want only the first text box to be in focus. To achieve this, I am utilizing another directive for focus control. Below is my script: <script> angular.module('MyApp',[]) ...

The alignment is off

<script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> <p text-align="right" id="demo" style="font-family:Comic Sans ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

Is there a way to transfer a JSON map object from Flask and then utilize it as a JavaScript object?

python server code from flask import Flask, render_template, request import os import sys import json data_raw = [('0', '1', '0', '0'), ('0', '0', '1', '0'), ('1', ...

Is it possible to use both the filter $select.search and the limitTo $select.infiniteCurrentLimit on a single ui-select field?

I am facing a challenge with my ui-select field which utilizes infinite-scroll functionality due to having a large number of options. However, it becomes cumbersome to scroll down and find the desired option among so many choices. <ui-select-choices ...

"Encountering a failure with PHP PDO prepared delete statement in MySQL while executing an Ajax

I am troubleshooting a PDO Prepared DELETE statement issue within a PHP file that is called using AJAX. Below is the AJAX call: var data = {action: "deleteTask", value: "1"}; $.ajax({ type: "POST", dataType: "json", url: "aja ...

What is the correct way to encode an HTML string in JavaScript?

I have identified a XSS Scripting vulnerability in my code and I want to prevent it. To do so, I am utilizing a Jquery Encoder for protection against XSS Scripting attacks. Below is the JavaScript code snippet: function test(response) { $('#test ...

When using onclick="location.href='page.html'", the page fails to load on Safari browser

I've been having trouble with getting onclick="location.href='link.html'" to work and load a new page in Safari (5.0.4). In my project, I am creating a drop-down navigation menu using the <select> and <option> HTML tags. I have ...

Load Angular modules dynamically

Is there a way to dynamically load a module (js, css and html) using a single directive at any point during the app's lifecycle? <my-module id="contacts"></my-module> The template for this directive looks like this <my-module id="con ...

Monitoring changes in session storage with AngularJS

In the sessionStorga, I have stored data from various controllers using a library called https://github.com/fredricrylander/angular-webstorage. The data is being successfully stored and is accessible within the current session. However, I am encountering a ...

Struggling with UI-Grid's single filter feature when dealing with intricate data structures?

I'm currently working with UI-Grid and facing a challenge while applying a filter to some complex data using their single filter example. Initially, everything runs smoothly when I use simple selectors. However, as soon as I attempt to delve one level ...

Ensure that site content remains visible above the table when refreshing the Ajax Table

Whenever I update the table, the content above it ends up below the table. This is frustrating because the content should not be affected by the refresh. How can I resolve this issue? <!DOCTYPE html> <html> <head> <titl ...

Ways to synchronize countdown timer on different tabs using the same link

Is there a method available to synchronize a React countdown timer across two separate tabs, for example: 1:46          ||   1:52 first tab     ||   second tab Appreciate any help! ...

Tips for keeping the header section anchored to the top of the page

I am having trouble getting the menu bar and logo to stick at the top of my header section in the template. I have been trying different solutions, including using the sticky.js plugin for almost 4 days now but it's not working. I also have parallax e ...

Tips for eliminating null values from a JavaScript object

I am currently facing an issue with a JavaScript object that consists of two arrays. At times, one of the arrays might be empty. I am attempting to iterate through the object using a recursive function, but I want to exclude any empty arrays or strings fro ...