Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
Why is my javascript while loop not working?

My while loop should, on each iteration, create an img tag, set its src, then add an event listener. This event listener fires on error event, which would be a 404, in the case the is not found. The images are stored in a local file, but I don't know how many files might be in each project folder. Images will be named 1, 2, 3, 4, etc. As soon as an error event has fired on one of the img tags, this will mean we have reached the end of the images for a particular project, and this event listener will change isLooping to false, and the while loop should stop executing at this point. However my browser just enters a state of perpetual loading. No errors in the console but browser will eventually crash. Why is this? I think it's a problem with how I have set up my while loop.

const GalleryProject = (function () {
  const galleryContainer = document.querySelector('.gallery-container')
  let isLooping = true

  function openProject(index = 1) {
    const imagesContainer = document.createElement('div')
    imagesContainer.classList.add('images-container')

    const bigImgTag = document.createElement('img')
    bigImgTag.classList.add('big')

    const smallImgTagContainer = document.createElement('div')
    smallImgTagContainer.classList.add('small-img-container')

    imagesContainer.appendChild(bigImgTag)
    imagesContainer.appendChild(smallImgTagContainer)
    galleryContainer.appendChild(imagesContainer)

    displayProjectInfo(index)
    loadBigImage(index)
    loadSmallImages(index)
  }

  function loadBigImage(index) {
    const bigImg = document.querySelector('img.big')
    bigImg.src = `assets/projects/single-bucket/${index}/main-image.jpeg`
  }

  const smallImgErrorHandler = function () {
    isLooping = false
    this.remove()
  }

  function loadSmallImages(index) {
    const smallImgContainer = document.querySelector('.small-img-container')
    let i = 1
    while (isLooping) {
      const img = document.createElement('img')
      img.addEventListener('error', smallImgErrorHandler)
      img.src = `assets/projects/single-bucket/${index}/${i}.jpeg`
      smallImgContainer.appendChild(img)
      i++
    }
  }

  function displayProjectInfo(index) {
    const textWrapper = document.createElement('div')
    textWrapper.classList.add('project-description-wrapper')

    const title = document.createElement('p')
    title.classList.add('project-title')
    title.textContent = projectData[index - 1].title

    const description = document.createElement('p')
    description.classList.add('project-description')
    description.textContent = projectData[index - 1].description

    textWrapper.appendChild(title)
    textWrapper.appendChild(description)
    galleryContainer.appendChild(textWrapper)
  }

  return { openProject }
})()

GalleryProject.openProject()
about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

This is not the correct way to program in JavaScript.

The loading of the images is going to be asynchronous, therefore, you need to wait for the load to be complete before you go on.

In other words, right now, you loop really fast adding new <img src=.../> tags without waiting for the image to be loaded or for the load to have failed. You need to do it asynchronously. This means create one image tag, wait for either success or failure. On success, try to load the next image. That means your code needs to change dramatically. The "while" loop is replace by these success/failure callbacks instead.


Update based on comments:

If you can instead get the total number of images for that one run, then having a loop based on that total number will be faster. This is because you'll give the browser all the URLs at once and in most cases it will attempt to load at least two images in parallel.

about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda