I started in JavaScript today, I'm trying to make this code that generates passwords while the button is disabled and when is enable the generator stops. The problem is that it only works once even with the button disabled. I tested it using just console.log('yes')
inside the while and it works fine, but when I add the rest of the code it only works once. What is the reason for this? I started today so I don't really know what to look for to solve my problem
this is the complete code
const pass = document.querySelector('#pass')
const newPassword = document.querySelector('#newPassword')
async function generatePass(){
document.querySelector('#Goal').disabled = true
while (document.querySelector('#Goal').disabled == true) {
await sleep(1)
console.log('yes')
newPassword.innerHTML = ''
if(pass.value === ''){
alert('Choose the password size!')
return
}
document.querySelector('#Goal').disabled = true
let charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let password = ""
for(var i = 0, n = charset.length; i < pass.value; i){
password = charset.charAt(Math.floor(Math.random() * n))
}
let result = document.createTextNode(password)
return newPassword.appendChild(result)
}
async function sleep(seconds) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000))
}
}
function breakgeneratePass(){
document.querySelector('#Goal').disabled = false
}
And this is just with the console.log('yes')
const pass = document.querySelector('#pass')
const newPassword = document.querySelector('#newPassword')
async function generatePass(){
document.querySelector('#Goal').disabled = true
while (document.querySelector('#Goal').disabled == true) {
await sleep(1)
console.log('yes')
}
async function sleep(seconds) {
return new Promise((resolve) => setTimeout(resolve, seconds * 1000))
}
}
function breakgeneratePass(){
document.querySelector('#Goal').disabled = false
}
CodePudding user response:
At the end of the while
loop you do:
return newPassword.appendChild(result)
This doesn't just break from the loop, it exits the whole generatePass
function.
You probably just meant:
newPassword.appendChild(result)