In our daily development, we often encounter a situation where we want to make a function execute only once, especially when some loops or timed execution.
Without further ado, just upload the code:
function runOnce(fn, context) { //Control the function to trigger return function () { try { fn.apply(context || this, arguments); } catch (e) { console.error(e);// Generally you can comment out this line} finally { fn = null; } }} // Usage 1:var a = 0;var canOnlyFireOnce = runOnce(function () { a++; console.log(a);}); canOnlyFireOnce(); //1canOnlyFireOnce(); // nothing canOnlyFireOnce(); // nothing // Usage 2:var name = "Zhang San";var canOnlyFireOnce = runOnce(function () { console.log("Hello" + this.name);});canOnlyFireOnce(); // Hello Zhang San canOnlyFireOnce(); // nothing // Usage 3:var obj = {name: "The lonely geese from the world", age: 24};var canOnlyFireOnce = runOnce(function () { console.log("Hello" + this.name);}, obj);canOnlyFireOnce(); //Hello, Tianya, canOnlyFireOnce(); // nothingBecause after the return function is executed once, fn = null sets it not null, so it will not be executed later. Post another code shared by others online, the principle is the same:
function once(fn, context) { var result; return function() { if(fn) { result = fn.apply(context || this, arguments); fn = null; } return result; };} // Usagevar canOnlyFireOnce = once(function() { console.log('Fired!');}); canOnlyFireOnce(); // "Fired!" canOnlyFireOnce(); // nothingThe above is a collection of the function examples for you to let JavaScript execute only once. If you need it, you can refer to it.