Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force javascript EventListener to execute once? [closed]

Tags:

I'm wondering is it possible for force a javascript event listener to, without the condition being true force it to execute once then continue listening for it's condition to be met to execute further?

like image 513
Skizit Avatar asked Feb 02 '11 19:02

Skizit


People also ask

Why should you remove event listeners once they are no longer used?

The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.

How do I stop event listener after clicking?

The removeEventListener() is an inbuilt function in JavaScript which removes an event handler from an element for a attached event. for example, if a button is disabled after one click you can use removeEventListener() to remove a click event listener.


1 Answers

var clickFunction = function (event) {
    //do some stuff here
    window.removeEventListener('click',clickFunction, false );

};
window.addEventListener("click", clickFunction, false);

This will let you fire the clickFunction once, as the magic of closure let the removeEventListener find the clickFunction.

No need to use a library just to get something simple done.

like image 159
Jlam Avatar answered Sep 24 '22 03:09

Jlam