Shuffle the setInterval function to display unpredictable images at varying intervals

I found JavaScript scripts for displaying random images and randomizing the setInterval function. I was able to get them to work together, but the images are changing too quickly. I want the images to change randomly between 1 minute and 10 minutes.

function randomImage() {
  var fileNames = [
    "http://i.imgur.com/YibF8aO.jpg",
    "http://ryanlb.com/images/other/images/getter-dragon-2.jpg",
    "http://i.imgur.com/JMgKg9O.jpg"
  ];
  var randomIndex = Math.floor(Math.random() * fileNames.length);
  document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';

}

function doSomething() {}

(function loop() {
    var rand = Math.round(Math.random() * 9999999999 );
    setTimeout(function() {
            doSomething();
            loop();  
    }, rand);
}());

randomImage();
setInterval(randomImage, doSomething());

WARNING: The images in the jsfiddle demo are flashing and rotating very quickly! Check out the jsfiddle example here

Answer №1

The reason for this issue is that the setInterval function is being called without specifying the 2nd parameter, which represents the time in milliseconds for the function in the 1st parameter to run. By leaving it undefined, it defaults to 0 milliseconds.

A better approach would be to use a recursive setTimeout instead.

Take a look at the modified version of your jsfiddle: https://jsfiddle.net/1a2b3c4d/

I have commented out the line that generates random output and instead, the content is updated every second without random time intervals.

Answer №2

Take a look at the following code snippet. Modify the image every 1 to 10 seconds.

<!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
        <script type="text/javascript">

            function getRandomInt(min, max) {
                return Math.floor(Math.random() * (max - min + 1)) + min;
            }

            function setNewInterval() {
                var randomInterval = getRandomInt(1000, 10 * 1000);
                console.log(randomInterval / 1000 + ' seconds');
                setTimeout(function () {
                    randomImage();
                }, randomInterval);
            }

            function randomImage() {
                var fileNames = [
                  "http://i.imgur.com/YibF8aO.jpg",
                  "http://ryanlb.com/images/other/images/getter-dragon-2.jpg",
                  "http://i.imgur.com/JMgKg9O.jpg"
                ];
                var randomIndex = getRandomInt(0, 2);
                document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';
                setNewInterval();
            }
            setNewInterval();
        </script>
    </head>
    <body>
        <div id="background" style="width: 700px; height: 500px;"></div>
    </body>
    </html>

Answer №3

It appears that your code may be a bit confusing. Within the loop function, you are currently calling doSomething which serves no purpose instead of calling randomImage. Additionally, you have two mechanisms for looping (one using setTimeout inside loop and another using setInterval where only the former is necessary).

function randomImage() {
  var fileNames = [
    "http://i.imgur.com/YibF8aO.jpg",
    "http://ryanlb.com/images/other/images/getter-dragon-2.jpg",
    "http://i.imgur.com/JMgKg9O.jpg"
  ];
  var randomIndex = Math.floor(Math.random() * fileNames.length);
  document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';

}

(function loop() {
  randomImage();                                        // change to a random image
  var rand = Math.floor(Math.random() * 5000) + 2000;   // get a number between 2 and 7 (5 + 2) seconds (you can change to whatever meets your need)
  setTimeout(loop, rand);                               // call loop after that amount of time is passed
}());                                                   // call loop at startup to get a random image on start
#background {
  width: 500px;
  height: 300px;
  background-color: red;
}
<div id="background"></div>

Answer №4

The reason for the issue is that doSOmething() is mistakenly placed as the second parameter of setInterval(). The second parameter of setInterval() should actually specify the interval at which the function should run indefinitely until stopped with clearInterval().

To address this, you can set a random interval between 1 minute and 10 minutes using the following code:

setInterval(randomImage, (60*1000) + Math.floor(Math.random()*9*60*1000));

If you want the function to run at a random interval each time, you should use a setTimeout instead of setInterval like so:

function randomImage() {
  // Image URL array
  var fileNames = [
    "http://i.imgur.com/YibF8aO.jpg",
    "http://ryanlb.com/images/other/images/getter-dragon-2.jpg",
    "http://i.imgur.com/JMgKg9O.jpg"
  ];
  // Get a random index
  var randomIndex = Math.floor(Math.random() * fileNames.length);
  // Set background image
  document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';
}

(function loop() {
    var between1and10min =  (60*1000) + Math.floor(Math.random()*9*60*1000);
    setTimeout(function() {
            randomImage();
            loop();  
    }, between1and10min);
}());

randomImage();

You can also combine the looping mechanism inside the randomImage function with a single line like so:

(function randomImage() {
  var fileNames = [
    "http://i.imgur.com/YibF8aO.jpg",
    "http://ryanlb.com/images/other/images/getter-dragon-2.jpg",
    "http://i.imgur.com/JMgKg9O.jpg"
  ];
  var randomIndex = Math.floor(Math.random() * fileNames.length);
  document.getElementById("background").style.background = 'url(' + fileNames[randomIndex] + ')';

  setTimeout(randomImage, (60*1000) + Math.floor(Math.random()*9*60*1000));
})();

You can view the working examples in the provided Fiddles: Fiddle 1 and Fiddle 2

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

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Using Google-Prettify with AngularJS

I have been attempting to implement Google Prettify in my AngularJS project. It seems to be functioning correctly on the main page, but once I navigate to another route using Angular (after ng-view), it stops working properly. You can check out the plunker ...

Verify using JavaScript whether the call is originating from a specific JSP

My global.js file serves as a common JavaScript file across my project. I recently added some code to a function named 'test' in this file. However, I only want this code to run when the function is called from a specific JSP file called home.j ...

Different methods of transferring PHP post information to JavaScript

Is there a cleaner and more elegant way to pass posted PHP variables to JavaScript for manipulation, rather than using inline JavaScript? I currently have a simple PHP form that posts data to specific variables and then uses inline JavaScript to handle the ...

An unforeseen repetition of jQuery Ajax calls

I'm currently working on an application that utilizes ajax calls to load content. However, I've encountered a situation where an ajax call goes into a loop but seems to end randomly. Below is the code sequence starting from a double click event l ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

Is using $window.location.reload(true) the same as manually pressing CTRL+F5?

I'm working on developing a feature called "version updated" component that displays a banner notifying users when the website has been updated and prompts them to reload. The challenge I'm facing is that some users are experiencing issues with c ...

Create an image on a node's backdrop using a library of graph theory/networking techniques

I have a set of data that I need to visually represent as a graph on a web browser. While creating the graph itself is not an issue, I am looking to dynamically draw unique icons for each node. These icons are specific to the characteristics of each node ...

Converting dates in JavaScript to the format (d MMMMM yyyy HH:mm am) without using moment.js

Looking to convert the date "2020-02-07T16:13:38.22" to the format "d MMMMM yyyy HH:mm a" without relying on moment.js. Here is one method being utilized: const options = { day: "numeric", month: "long", year: "numeric", } var date1 = new Date ...

Refine JSON data by selecting only distinct key/value pairs

My JSON object has the following structure: var theSchools = { Bradley University: "bru", Knox College: "knox", Southern Illinois University Edwardsville: "siue",… } I am trying to find a way to retrieve the school name (key) based on the schoo ...

Guide to fetching external data with Next.js and importing the component into a different file

I have implemented the following code in my pages/github file, and when I navigate to localhost:3000/github, the code runs successfully and returns JSON data. function GithubAPI(props) { // Display posts... return (<div>{props.data.name}</div& ...

A guide on effectively utilizing BehaviorSubject for removing items from an array

Currently, I am working on an Angular 8 application that consists of two components with a child-parent relationship. It came to my notice that even after removing an item from the child component, the item remains visible in the parent component's li ...

Switch between showing or hiding at least three divs

I'm currently using a simple script that toggles the visibility of two div elements: <script type='text/javascript'> $(window).load(function(){ function toggle_contents() { $('#page1').toggle(); ...

AngularJS UI router regular expressions allows for dynamic and flexible routing

I'm attempting to find a parameter with two possible values: 'current' or a number with at least 10 digits. Here's what I've tried: url: '/history/{code:^current$|^[0-9]{10,}$}' Although this regular expression suc ...

PHP MySQL table submission button

Here is the content I have: <table class="sortable table table-hover table-bordered"> <thead> <tr> <th>CPU</th> <th>Speed</th> <th>Cores</th> <th>TDP</th> <th> ...

Troubleshooting Cloud Functions: Fixing functions.logger.log not Functioning

Whenever a user updates the chat/{id} documents, this function is triggered. const functions = require("firebase-functions"); exports.onChangedChat = functions.firestore .document('chat/{id}') .onWrite((change, context) => { fun ...

Capturing user inputs in PHP or AJAX

Is there a way to capture keystrokes on a web page regardless of where the user is focused? For example, if someone has the webpage open and they press '1', can it trigger an action? And if they press '2', can something else happen wit ...

Access the CSV file using Office365 Excel via a scripting tool

Objective I want to open a CSV file using Office365's Excel without actually saving the file on the client's machine. Challenge The issue with saving raw data on the client's machine is that it leads to clutter with old Excel files accumu ...

How can I display the Bootstrap 5.3.0 Collapsible button on this basic website?

I've been struggling to implement a Bootstrap Collapsible on my web page using Bootstrap version 5.3.0. I've tried different approaches but I can't seem to get it to work. All I need is a Collapsible that contains a few links, which should b ...

How can I use the select2 jQuery plugin with the tags:true option to ensure that selected choices do not appear again in the dropdown menu?

Transitioning to select2 for tagging from a different plugin, I'm facing a gap that I need to address in select2's functionality. Let's consider an example. Suppose my list of choices (retrieved server-side via Ajax request) is: "Dog", "Ca ...