Seeking assistance with implementing setInterval and clearInterval functionalities in JavaScript programming

I'm currently working on a web widget that loads images from different directories based on the selection made in a drop-down list. If "Option 1" is chosen, it should fetch images from one directory at 7-second intervals. Choosing "Option 2" selects a different directory for image loading, also at 7-second intervals. I've implemented setInterval in JavaScript to achieve this functionality. While Option 1 works smoothly with the correct time interval, selecting Option 2 causes the interval to decrease from 7 seconds. I attempted to use clearInterval following various solutions, including guidance from this resource, but without success.

Here's a snippet of my code:

selectCity.addEventListener("change", () => {

    celeb.src = `${directory}/image1.png`;

    images = [];

    images[0] = `/${directory}/image1.png`;
    images[1] = `/${directory}/image2.png`;
    images[2] = `/${directory}/image3.png`;

    var setint = window.setInterval(changeImage, 7000);
    var x = 1;

    function changeImage() {
      celeb.src = images[x];
      console.log(images[x]);
      x++;
      if (images.length == x) {
        x = 0;
        window.clearInterval(setint);
        setint = window.setInterval(changeImage, 7000);
      }     
    }
}

I'm looking to utilize clearInterval each time "selectCity" changes. As a newcomer to HTML and JavaScript, I would appreciate any advice or suggestions on what might be wrong with my code.

Answer №1

Generally speaking:

  • If you require a function to be called continuously, use the setInterval method.
  • On the other hand, if you wish to delay the execution of a function, opt for the setTimeout method.

In your specific scenario, where you need to change an image with a delay when the value of selectCity changes, it is recommended to utilize setTimeout.

Here's an example:

let currentIndex = 0

selectCity.addEventListener('change', () => {
  setTimeout(() => {
    if (images.length < currentIndex) {
      celeb.src = images[currentIndex]
      currentIndex += 1
    }
  }, 7000)
})

Try using setTimeout in your browser:

document.getElementsByTagName('button')[0].addEventListener('click', function() {
  setTimeout(() => console.log('Clicked'), 5000)
})
<button>Console after 5 seconds</button>

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

Are jQuery plugins offering accessible public functions?

I am currently working on enhancing the functionality of a jQuery plugin. This plugin serves as a tag system and utilizes autocomplete provided by jQuery UI. Presently, there is no direct method (aside from parsing the generated list items) to determine ...

Outline a table element without altering the dimensions of the cell

When creating a diagram in an HTML table, I encountered a challenge. The TD elements have fixed dimensions, and I wanted to highlight this div with a border or circle. However, when I attempted to do so using CSS, it deformed the div. I couldn't use ...

Hover effect for Twitter-like buttons

Can someone help me figure out how to create a link control similar to Twitter's functionality? I'm referring to the way that on a tweet page, when you hover over a tweet, links appear for reply, delete, and favorite, but disappear when not hove ...

"jQuery Hide-and-Seek: A Fun Way to Manip

I am facing a challenge with a set of divs that I need to dynamically show and hide based on user interactions with questions. Essentially, the user will be presented with a question. Based on their answer, specific content with a title and description wi ...

Use Google Maps filters in combination with checkboxes

I am seeking assistance with the following task: I need to develop a map that displays markers when the user clicks on an input checkbox. For example: When I click on "hotels," only hotels are displayed on the map. If I uncheck the "hotels" option, the ho ...

What is the proper way to enable the Google Analytics cookie only once another consent cookie has been set and is marked as "true"?

I am currently using React/Nextjs on my website along with the react-cookie-consent library. This setup generates a pop-up where users can agree to the cookie policy, and if they do, a CookieConsent with the value "true" is set. In addition to this, I wis ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Tips for maintaining the visibility of the dynamic submenu while hovering over either the parent menu or submenu in vuejs

I'm currently working on a dynamic sidebar in vuejs and I need some assistance. The issue I'm facing is that I want the submenu to remain open when hovering over either the parent menu or the submenu itself. However, when I move the mouse away fr ...

When beginning a new React project, I encounter this issue

Every time I try to run npm start, an error pops up. How can I fix this issue? ...

Exploring Vue.js3: Simplifying Nested Array Filtering

Currently, I am in the process of sifting through an Array that contains nested arrays. To handle this task, I utilized computed and crafted a function called filteredEgg(). However, I seem to be overlooking something, as I'm only returning the main ...

Generate a fresh object with distinct identifiers

I am interested in creating a new object, utilizing unique keys consisting of comma-separated IDs. For instance, I have: const d = { "1,2,3,4,5,6,7,8,9,10": [ "created_by", "modified_on", "external_o ...

Automatically generate the first user on the Parse Server system

Is it feasible to programmatically create a User on Parse server without the need for sign up? More information can be found at https://github.com/parse-community/parse-server We attempted this using cloud code. var user = Parse.User(); user.setUserna ...

Steps for fixing the error "Fixing the MongooseServerSelectionError: Incorrect message size while trying to connect to MongoDB

Encountering a problem when attempting to link up with my MongoDB database using Mongoose in a Node.js program. The error message reads: Cannot connect to the database MongooseServerSelectionError: Invalid message size: 1347703880, maximum allowed: 67108 ...

Countdown timer that counts down in reverse when the browser is minimized

I am currently working on a JavaScript project where I have implemented a countdown timer in seconds. Once the timer hits zero, it triggers a specific function. The timer functions correctly, however, if the browser enters sleep mode or is minimized, the ...

How can I place a new ThreeJS child element at the front and center of a scene?

I have been working on a webpage that is inspired by the CSS3D molecules sample from ThreeJS's library. You can check out the original sample here. In my project, I am dynamically creating new nodes (atoms) and attaching them to existing nodes. Once ...

Retrieving the content of a dynamic template with Angular-UI-Router

Currently, I am in the process of developing an angular application utilizing angular-ui-router. The backend of the application consists of a REST api that provides a form URL based on a specific ticket id. My aim is to dynamically set the template in app. ...

The subsequent menu selection will be based on the chosen menu value

I am attempting to accomplish the following: https://i.sstatic.net/JffUWC02.png Essentially, I need a select options menu with labels where selecting an option will display a corresponding value. These values should then become labels for a second selec ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...

Encountering a 404 error while using THREE.ImageUtils.loadTexture in three.js

My first attempt at using three.js involves loading a 3D model, but I'm encountering an issue with texture loading. loader.load('models/asteroid_OBJ/asteroid OBJ.js', function (geometry, materials) { var material = new THREE.MeshLambertM ...

Using Express to Deliver Static Content to Subdirectories

I am currently using Express to serve a React application that was bootstrapped with Create React App. The project has the following directory structure: |--client/ | |--build/ | | |--static/ | | | |--main.css | | | |--main.js | ...