I don't know how to break or return from addEventListener
Here I get "Undefined label 'testfunc'" error
testfunc:
test.addEventListener("click", function(){
console.log("TEST")
break testfunc
})
Here I get "TEST" everytime i click but I want it only to console.log("TEST") only once
function testfunc(){
test.addEventListener("click", function(){
console.log("TEST")
return
})
}
CodePudding user response:
You cannot return testfunc from an event in your listener since your listener anonymous function will be executed on click event, after testfunc is executed.
What you can is prevent your event listener anonymous function to be reexecuted. To do so, write a condition with a variable which will be set to true after it is executed once.
let isClicked = false;
function testFunc(){
document.addEventListener("click", function(){
if (isClicked) return;
// Will be executed once.
console.log("TEST");
isClicked = true;
})
}
testFunc();
CodePudding user response:
you can create some variable and put there flag (true/false), for example:
let isClicked = false;
function testfunc(){
test.addEventListener("click", function(){
if (isClicked) return;
console.log("TEST")
isClicked = true
})
}
