Home > database >  JavaScript How to loop between 2 numbers
JavaScript How to loop between 2 numbers

Time:10-21

Im trying to make a loop where i have let sum = 0 When i click on a button Sum goes to 1 and when i press the button again it goes back to 0, and loop it every time i press the button

let sum = 0


button.addEventListener("click", loop())


function loop(){

}

CodePudding user response:

Lets call it toggle not loop, it will be like this

function toggle(){
 sum = sum==0 ? 1:0;
}

so every time it will switch between these 2 numbers

CodePudding user response:

First off you should remove the ( ) from the listener callback.

Try this:

let sum = 0

button.addEventListener("click", loop)

function loop(){
  sum = sum ? 0 : 1
}
  • Related