Converting a Click Event to a Scheduled Event using JavaScript and AJAX

Currently delving into the world of AJAX & JavaScript, I have a question for the knowledgeable individuals out there.

I am curious to know how I can transform the code below from an OnClick event to a timed event.

For instance, I would like to refresh the content of the "showlist" DIV every 5 seconds...

I am aware that posting working code is not permitted here, but sharing my non-functional code would only add to the confusion.

I am gradually grasping the basics and any help or advice would be greatly appreciated.

<!DOCTYPE html>
<html>
<head>
<script>

function loadXMLDoc()
{

var xmlhttp;
if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
else
    {
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

document.getElementById("showlist").innerHTML=xmlhttp.responseText;

}
}

xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();

}
</script>
</head>

<body>

<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>

</html>

Answer №1

To enhance the loadXMLDoc function, you can incorporate the use of setTimeout. Take a look at this sample:

function loadXMLDoc() {

    var xmlhttp,
        timer;

    if (window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
    } else {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("showlist").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.onerror = function() {
        clearTimeout(timer);
    };

    xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
    xmlhttp.send();


    timer = setTimeout(loadXMLDoc, 5000);
}

This function initiates an AJAX request and establishes a timeout of 5 seconds. Additionally, I included a basic onerror callback to reset the timer as needed.

Answer №2

Back in the day, I created a custom television that would change its 'screen' every 3 seconds automatically.

If you're interested, feel free to take a look at my code below:

// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array containing picture names
var myPics = ['img-screen1.png','img-screen2.png'];
// Checking the number of items in the array
var totalPics = myPics.length;
// The function that loops through and displays each picture one by one
var i = 0
function loop() {
    if(i > (totalPics - 1)){
        i = 0;
    }
    myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
    i++;
    loopTimer = setTimeout('loop()',3000);
}
loop();

Feel free to adapt this code for your own project. If you have any questions or need clarification, don't hesitate to reach out :).

Remember to update the array whenever you add new items to your showlist!

Answer №3

If you include this code snippet within the same script tag after your loadXMLDoc function, it will automatically execute and call your function every 5 seconds in a recursive manner. Using setTimeout ensures that the function is called repeatedly without missing any cycles, unlike setInterval which may skip a cycle if the JavaScript engine is overloaded:

(function doMeSelf(){
    setTimeout(function(){
        loadXMLDoc();
        doMeSelf();
    },5000);
})();

By encapsulating the function definition within parentheses followed by (), it creates an immediately invoked function expression.

To understand more about this concept, refer to the following question: What do parentheses surrounding an object/function/class declaration mean?

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

Next.js | Error: Attempting to access a property of an undefined value (property name: 'secret')

I encountered an issue while trying to authenticate the API routes in next.js. The page level authentication is working properly, but when attempting to fetch the session in the API routes, I am facing an error. Error - TypeError: Cannot read properties of ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

What is the best way to fetch JSON data in React from the start and then manipulate it as needed before exporting to another file within my application?

I have a scenario where I need to fetch data from a MongoDB database using async/await fetch() and save it in a file called data.js. However, I am facing an issue with React executing "in parallel" due to the nature of async/await. This makes it difficult ...

Ways to enhance the appearance of the parent element when the radio button is clicked

Hey there! So, I have a situation where I'm working with two radio buttons and I want to apply certain CSS styles to the parent box (<div>) when a radio button is selected (checked). Here's how I want it to look: box-shadow: 0 0 5px #5cd05 ...

Get alerts from Twitter pushed to my site

Is it possible to create a web application that utilizes JavaScript to receive notifications from Twitter? I want my website app to send me notifications whenever a person I follow posts a new article. I'm having difficulty with this task and would gr ...

npm encountered an error while trying to install selenium-webdriver using the npm install command

My operating system is Windows Server 2008 R2 EE and I have the npm package manager installed. I am attempting to install the Selenium Webdriver package using the command below. Command: npm install selenium-webdriver However, when running this comma ...

Learn how to efficiently pass multiple props using a loop in Vue

I am dealing with an object that has multiple properties. Typically, I know which props I want to pass to my component and do it like this: <component :prop1="object.prop1" :prop2="object.prop2" :prop3="object.prop3" /> However, I want to pass the ...

Implementing a function to specify size limits

As a newcomer to the world of JavaScript, I am facing a particular challenge. My goal is to add a conditional statement in my code that will only execute on screen sizes larger than 768px. $(window).on('scroll', function () { if ($(window ...

Tips for sending attributes to jQuery autocomplete

I'm facing a major issue with implementing a jquery autocomplete feature, and JavaScript isn't my strong suit. Currently, I'm using the jquery.auto-complete plugin available at: https://github.com/Pixabay/jQuery-autoComplete, which is an up ...

Storing multiple values of dynamically added elements in a single variable and accessing them within a function

Is it possible to store multiple values into a single variable and then access them in a setTimeout function? $(document).ready(function (){ div ({'div':'#noo','auto':'true','pos':'top',' ...

Removing users from a Socket.IO chat room using Node.js

I am facing an issue with removing users from Socket.IO when their browser is closed. The 'user' in the array 'users[]' is not getting removed or updated. Additionally, I would like to update the users on the client side as well. Can so ...

Is your blockui overlay failing to cover the entire page?

I have implemented blockui to display a "Wait ... loading" popup on my webpage. It is mostly working fine, but I am facing a small issue where the overlay does not cover the entire width of the scroll window when I scroll right (although it covers the full ...

exploring the ins and outs of creating computed properties in TypeScript

How can I store an object with a dynamically assigned property name in an array, but unsure of how to define the array properly? class Driver { public id: string; public name: string; constructor(id , name) { this.id = id; th ...

Error with Google Maps Display

My goal is to achieve two things with the code snippet below: If the geocode process is unsuccessful, I want to prevent the map from being displayed (currently, I've only hidden the error message). If the geocode process is successful, I only want t ...

What error am I making in the Date calculator for the select box using Javascript/jQuery?

$(.dateselboxes) .change( function(){ var y; y=$("#year").val(); var m; m=$("#month").val(); var d; // check for leap year var isLeapYear; if(y%4==0) { if(y%100==0) { if(y%400==0) {isLeapYear=true;} else {isLeapYear=false;} } ...

Guide to setting the first tab as the default tab using Thymeleaf, Css, and Bootstrap

I am currently working on a project where I need to dynamically create tabs based on a list retrieved from my Spring backend using Thymleaf and Bootstrap. While I have managed to successfully create the tabs and content, I am facing an issue where the fi ...

Constant updating of webpage elements without the need for a complete page reload

Is there a way to refresh a top bar similar to Facebook, where the number of messages updates without refreshing the entire page? I know how to do this if the top bar is separate from the main page using meta tags, set timeout, or a refresh tag. However, ...

When passing an array from jQuery to PHP using Ajax, the value displayed is simply "Array" instead of the actual

Could anyone please assist me in identifying my mistake? js file: //Checkboxid is an array that gets filled using .push(); $.ajax({ type: "POST", url: "test.php", dataType: 'html', data: { data: Checkboxid }, success: functio ...

Developed a new dynamic component in VUE that is functional, but encountered a warning stating "template or render function not defined."

I'm currently working on a dynamic markdown component setup that looks like this <div v-highlight :is="markdownComponent"></div> Here's the computed section: computed: { markdownComponent() { return { temp ...

Instructions on how to dynamically show specific text within a reusable component by utilizing React and JavaScript

My goal is to conditionally display text in a reusable component using React and JavaScript. I have a Bar component that I use in multiple other components. In one particular ParentComponent, the requirement is to show limit/total instead of percentage va ...