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
Put whatever you are doing in a normal
for
loop and keep a variable to control the loop.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
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.