skip to Main Content

I created a function to go through an array to load some products on my website, then I created an element.eventListener to run another different array. I don’t want the first function to keep going and keep loading products from the first array. I only want the eventListener to work when clicking a button.

This is what I am trying:

function cargadorProductos(productos) {
    
    contenedorProductos.innerHTML="";

    productos.forEach(producto => {
        let div = document.createElement('div');
        div.classList.add ("producto");
        div.innerHTML = `
        <img  class="foto"  src="${producto.img}" alt="cara"> 
    <div class="descripcion"> <h3> Brocha difuminadora </h3> </div>
    <div class="precio"> <h3>${producto.precio}</h3> </div>
    <button class="boton" type= "button" id= "${producto.id}"> Comprar! </button> 
        `

        contenedorProductos.append(div); 
    });

}

cargadorProductos(productos); 
 ** // this is first function, all good till here. but then I want to stop this and run below.     **



  botonCara.addEventListener('click',  () => { 
       

    cara.forEach(cara => {
        let div = document.createElement('div');
        div.classList.add ("producto");
        div.innerHTML = `
        <img  class="foto"  src="${cara.img}" alt="cara"> 
    <div class="descripcion"> <h3> Brocha difuminadora </h3> </div>
    <div class="precio"> <h3>${cara.precio}</h3> </div>
    <button class="boton" type= "button" id= "${cara.id}"> Comprar! </button> 
        `

        contenedorProductos.append(div); 
       
    });    **//this works just fine, just want to stop  cargadorProductos(productos);   **   

2

Answers


  1. Put whatever you are doing in a normal for loop and keep a variable to control the loop.

    let running = true;
    
    ...
    
    for(let i = 0; running  && i < productos.length; i += 1) {
      const producto = productos[i];
      const div = document.createElement('div');
      div.classList.add ("producto");
    
      div.innerHTML = `
        <img  class="foto"  src="${producto.img}" alt="cara"> 
        <div class="descripcion"> <h3> Brocha difuminadora </h3> </div>
        <div class="precio"> <h3>${producto.precio}</h3> </div>
        <button class="boton" type= "button" id= "${producto.id}"> Comprar!</button>`;
    
      contenedorProductos.append(div);
    }
    

    If you want it to stop set running = false from somewhere outside.


    As a lot of other people will also tell you. I don’t even know if this is useful as I can imagine that this loop runs through in a few milliseconds max. So the window to trigger a stop of this is practically 0 unless you are dealing with tens of thousands of elements

    Login or Signup to reply.
  2. You won’t be able to achieve this with a for loop. You need to be able to run the functions in parallel. One way to do this would be to use setInterval or setTimeout

    Here is a sample implementation:

    The idea here is that the function inside the setinterval will keep running unless interrupted by the function at the click of a button. When the button clicks, it shall clear the current running timer & hence the loop.

    // Dummy data & Variables
    var productos = [{img: "", precio: "One", id: 1}, {img: "", precio: "Two", id: 2}, {img: "", precio: "Three", id: 3 }]
    var cara = [{img: "", precio: "NewOne", id: 1}, {img: "", precio: "NewTwo", id: 2}, {img: "", precio: "NewThree", id: 3 }]
    
    var contenedorProductos = document.getElementById("contenedorProductos");
    var botonCara = document.getElementById("botonCara");
    
    // Variables to control the load
    var currentIndex = 0, interval = 1000, timer = 0;
    
    function cargadorProductos(productos) {
      contenedorProductos.innerHTML = "";
      timer = setInterval(() => {
        let producto = productos[currentIndex++];
        let div = document.createElement('div');
        div.classList.add("producto");
        div.innerHTML = `<img  class="foto"  src="${producto.img}" alt="cara"> 
        <div class="descripcion"> <h3> Brocha difuminadora </h3> </div>
        <div class="precio"> <h3>${producto.precio}</h3> </div>
        <button class="boton" type= "button" id= "${producto.id}"> Comprar! </button>`
        contenedorProductos.append(div);
    
        if (currentIndex == productos.length) clearInterval(timer);
      }, interval);
    }
    
    cargadorProductos(productos);
    
    botonCara.addEventListener('click', () => {
      clearInterval(timer);
      cara.forEach(cara => {
        let div = document.createElement('div');
        div.classList.add("producto");
        div.innerHTML = `<img  class="foto"  src="${cara.img}" alt="cara"> 
        <div class="descripcion"> <h3> Brocha difuminadora </h3> </div>
        <div class="precio"> <h3>${cara.precio}</h3> </div>
        <button class="boton" type= "button" id= "${cara.id}"> Comprar! </button>`
        contenedorProductos.append(div);
      });
    });
    <button id="botonCara">botonCara</button>
    <div id="contenedorProductos"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search