Home > Article > Web Front-end > Three common methods to make functions in js have only one valid call
How to make a function in js only executed once? We sometimes have this requirement, that is, to execute a function only once, and the second call will not return any valuable value or report an error. The following will show the methods used through three small demos, as personal notes.
1. Implemented through closure.
<script> window.onload = function () { function once(fn) { var result; return function() { if(fn) { result = fn.apply(this, arguments); fn = null; } return result; }; } var callOnce = once(function() { console.log('javascript'); }); callOnce(); // javascript callOnce(); // null } </script>
2. After the first call, leave the func function value empty. func= function(){};
<script> var func = function () { alert("正常调用"); func= function(){}; } func(); func(); </script>
3. Set a value and use boolean to control subsequent calls.
<script> window.onload = function () { var flag = true; function once() { if (flag) { alert("我被调用"); flag = false; } else { return; } } once(); once(); } </script>
For more related tutorials, please visit JavaScript Video Tutorial