How to pause and continue after an event a For?

Asked

Viewed 91 times

0

I have that code here:

function aparecer(){
  const array1 = [1,2,3,4,5,6,8,9,10];
    for (let i=0; i < array1.length;i++){
      const lugar = document.getElementById('local');
     
     const ul = document.createElement('UL');
     const valor = document.createTextNode(array1[i])
      ul.appendChild(valor);
      
      lugar.appendChild(ul)
      break
    
      } 
    
}

function desaparecer(){
 document.getElementById('local').innerHTML= '';
  
}
<html>
  <button onClick='aparecer()'> Aparecer </button>
  
  <button onClick='desaparecer()'> Desaparecer </button>
  
  <div id='local'> </div>
  
</html>

And I want every click to appear only 3 numbers. Example: I clicked on aparecer, ai appears: 1,2,3 clicked again, appears 4,5,6 clicked again, 7,8,9 and just after clicking again appear only the 10.

Always creating a new UL, and not replacing the current.

How do I do that ?

1 answer

2


var current  = 0;
var array1 = [1,2,3,4,5,6,8,9,10];

function aparecer(){
	//verifica se o current é maior do que o array
	if ( (array1.length - 1) < current ) {
		alert("oi");
		//isso deveria parar a função
		return false;
	}
	for (var i= current; i <= (current + 2); i++){
		const lugar = document.getElementById('local');

		const ul    = document.createElement('UL');
		const valor = document.createTextNode(array1[i])
		ul.appendChild(valor);

		lugar.appendChild(ul);

	} 
	current = i;
}

function desaparecer(){
 current = 0;
 document.getElementById('local').innerHTML= '';
  
}
<html>
  <button onClick='aparecer()'> Aparecer </button>
  
  <button onClick='desaparecer()'> Desaparecer </button>
  
  <div id='local'> </div>
  
</html>

  • Perfect, about the parade, tried to use break; to stop and continue; to shoot from where you left off?

  • @Marcelorafael Otimo Marcelo, thank you very much, but a doubt, if I want to change the numbers by changing them? Example: Click and appear: 1,2,3 Click again and appear: 4,5,6 instead of 1,2,3, in this case, replacing 1,2,3 by 4,5,6

  • Just go ahead and clean the container with element.innerHTML = ''

Browser other questions tagged

You are not signed in. Login or sign up in order to post.