automated JavaScript image array generation

I have a coding project involving changing images in an array. I've successfully set up the automatic image change, but now I want to customize the timing between each image transition. The code is being written in Dreamweaver.

Here's the current code snippet:

<!DOCTYPE html>
<html>
<body>


<img src="image1.png"   width="74" height="208" id="image1">
<br>
<button onclick="clearInterval(MyVar)">Stop Sequence</button>

<script>

MyVar = setInterval(ChangeImages, 1000)

function Start() {
myVar = setInterval(ChangeImages, 1000)
}


var Images = ["image1.png", "image2.png","image3.png","image4.png"];


var image = document.getElementById("image1");




function ChangeImages()
{
    if (image1.src.match(Images[0]))

     {
        image.src = Images[1];

    } else if (image1.src.match(Images[1]))

     {
        image.src = Images[2];
    } else if (image1.src.match(Images[2]))

     {
        image.src = Images[3];
    } else if (image1.src.match(Images[3]))

     {
        image.src = Images[0];

    }
}
</script>

<br>

<Button onclick="Start() ">Resume</button>

</body>

</html>

Any assistance on how to adjust the timing would be highly appreciated.

Thank you!

Answer №1

To vary the number of seconds each time, consider using setTimeout instead of setInterval in this scenario. You can then implement a callback function at the end of ChangeImages and utilize a random number generator to determine the milliseconds value. In the provided example, I have set it to either 1000, 2000, or 3000 milliseconds.

<img src="image1.png" width="74" height="208" id="image1">
<br>
<button onclick="clearInterval(myVar)">Stop Sequence</button>

<script>

function Start() {
   myVar = setTimeout(ChangeImages, randomInterval(1,3));
}
var Images = ["image1.png", "image2.png","image3.png","image4.png"];
var image = document.getElementById("image1");
function randomInterval(min,max)
{   
    var number = (Math.floor(Math.random()*(max-min+1)+min))*1000;
    console.log(number);
    return number;
}

function ChangeImages(){
    if (image1.src.match(Images[0])){
        image.src = Images[1];
    }
    else if (image1.src.match(Images[1])){
        image.src = Images[2];
    }
    else if (image1.src.match(Images[2])){
        image.src = Images[3];
    }
    else if (image1.src.match(Images[3])){
        image.src = Images[0];
    }
    Start();
}
</script>

<br>

<Button onclick="Start() ">Resume</button>

EDIT

function Start(timeout) {
   myVar = setTimeout(ChangeImages, timeout);
}
var Images = ["image1.png", "image2.png","image3.png","image4.png"];
var image = document.getElementById("image1");

function ChangeImages(){
    if (image.src.match(Images[0])){
      image.src = Images[1];
      Start(1000);
    }
    else if (image.src.match(Images[1])){
      image.src = Images[2];
      Start(2000);
    }
    else if (image.src.match(Images[2])){
      image.src = Images[3];
      Start(3000);
    }
    else if (image.src.match(Images[3])){
      image.src = Images[0];
      Start(4000);
    }

}

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

Guidelines for choosing and uploading a file using Ionic

Is there a way to upload a PDF file to a server using the $cordovaFileTransfer plugin? I currently have an input field like this: <input type="file" onchange="angular.element(this).scope().fileNameChanged(this)"> How can I retrieve the pathForFile ...

Toggle the visibility of the identical div

I am facing a challenge with dynamically hiding and showing various div elements on my website. I have managed to achieve this using show/hide, but the issue arises when I need to show/hide some of the same fields repeatedly. The script works fine on the f ...

What could be the reason that my JSON request is not functioning properly?

I am currently working on creating a movie search application. This project marks my first time delving into json and I'm facing some issues with my code. As of now, I have it set up and running smoothly on localhost through xampp. On submitting the ...

Is it possible to generate markers using JavaScript in Vue2Leaflet instead of relying on components?

According to the documentation on Vue2Leaflet, a marker can be created using <l-marker :lat-lng="latLng" ></l-marker>. However, due to certain requirements, I need to create the marker from JavaScript rather than within the <template>< ...

"Integration of jQuery and Twitter Bootstrap for creating a dynamic progress bar

Looking for guidance on creating a loading progress bar effect when clicking a button? Here's the code snippet I currently have: <div class="progress"> <div class="bar" style="width: 0%;"></div> </div> What steps should b ...

Obtain the data from the array and incorporate it into the fresh PHP code

Having a major issue as I am unsure of how to extract values from an array where the value is transformed into the key in a new array. The original array is presented below: Array ( [0] => Array ( [ID] => 250602 ...

Combining a pair of strings to form an array or object

I have a dilemma with combining two strings into one array or object. 1: [atty_hourly_rate],[paralegal_hourly_rate],[advanced_deposit] 2: 250,150,500 My main goal is to access the value 500, which corresponds to advanced deposit. The order of the strin ...

What is the best way to display multiple sets of table data on a single page without any connections between them?

Is there a way to combine data from two tables (dept_db, role_db) and display it on my createUsers page? I am looking for a solution where the page only needs to be rendered once to retain the previous query results. Thank you. exports.createUsers = func ...

What is the best way to generate an array within a function and then send it back in C programming?

My goal is to create a function that generates an integer array with a random size and random characters, then returns it. Since the array's size is unknown, I can't declare it as a global variable, so I created a separate function for that purpo ...

Exploring the world of 3D with wireframes and unique object materials

I need to retrieve the wireframe of an object that I have loaded using OBJMTLLoder. Below is the code snippet I am currently using: var loader = new THREE.OBJMTLLoader(); loader.load( 'obj/male02/male02.obj', 'obj/male02/mal ...

Implementing dynamic checkbox values depending on a selection from a dropdown menu in Angular

In my checkbox list, I have various Samsung mobile models and two offers available. $scope.offers = [ { id: "as23456", Store: "samsung", Offer_message:"1500rs off", modalname: "Samsung Galaxy You ...

Exploring the distinctions between width/height measurements and the image attribute in styling

What is the benefit of using a style image attribute instead of individually coding width and height for each image? ...

Tips for looping through multi-dimensional arrays in jsredner

I have the JSON data provided below that represents a music score: [ { "Name":"Billy in the Lowground", "Key":"A", "chords":[ [ "G", "", "D", "" ], // Addition ...

Instructions for designing a striking image header on a webpage with the combination of PHP and HTML

I am working on creating an Image Header Page in PHP, where I can include some URLs with non-SSL to ensure a fully SSL encrypted webpage. One example of this is the service provided by DuckDuckGo: http://images.duckduckgo.com/iu/?u=http://4.bp.blogspot.co ...

Filtering in AngularJS based on a specific ID

Currently, I am dealing with a JSON encoded response from PHP that looks like this... [ {"ID":"149","IDusr":"4","aut_more_info":"good","doc_name":"img1838142879.jpeg","doc_type":"jpg"},{"ID":"149","IDusr":"4","aut_more_info":"good","img5733250433.jpeg","d ...

Tips for transferring a DateTime object from NodeJS Sequelize to MSSQL

Help needed with passing an 'UpdateDate' field using Sequelize in my NodeJS project. The error 'Conversion failed when converting date and/or time from character string' keeps popping up. I have tried using Date.now() and new Date().toI ...

Searching for English words within a string using Javascript

Looking to identify English words (minimum of 4 letters) within a single string. Example: hello123fdwelcome => ["hello", "welcome"]; Any recommendations for a solution or JavaScript library to match English words? Thank you! ...

Exiting or returning from a $scope function in AngularJS: a guide

There are times when I need to exit from my $scope function based on a certain condition. I have attempted to achieve this using the return statement. However, my efforts have been in vain as it only exits from the current loop and not from the main scop ...

Choose the text by clicking on a button

I currently have: <span class="description">Description 1</span> <button class="select">Select!</button> <span class="description">Description 2</span> <button class="select">Select!</button> <span clas ...

gulp-babel is failing to generate any output files or is experiencing issues with its functionality

I am currently developing a JavaScript library and my goal is to transpile all ES6 code to the ES5 standard in order to increase browser support. To achieve this, I have decided to utilize Babel with Gulp tasks. In preparation, I have installed the necess ...