Example of js function that only executes once

  • 2021-07-04 18:07:56
  • OfStack

In our daily development, we often encounter one such situation: we want a function to be executed only once, especially when it is executed in one loop or timing.

Needless to say, go directly to the code:


function runOnce(fn, context) { // Control makes the function only trigger 1 Times 
  return function () {
    try {
      fn.apply(context || this, arguments);
    }
    catch (e) {
      console.error(e);//1 You can comment out this line 
    }
    finally {
      fn = null;
    }
  }
}
 
// Usage 1:
var a = 0;
var canOnlyFireOnce = runOnce(function () {
  a++;
  console.log(a);
});
 
canOnlyFireOnce(); //1
canOnlyFireOnce(); // nothing
canOnlyFireOnce(); // nothing
 
// Usage 2:
var name = " Zhang 3";
var canOnlyFireOnce = runOnce(function () {
  console.log(" How do you do " + this.name);
});
canOnlyFireOnce(); // Hello, Zhang 3
canOnlyFireOnce(); // nothing
 
// Usage 3:
var obj = {name: " Lonely Wild Goose at the End of the World ", age: 24};
var canOnlyFireOnce = runOnce(function () {
  console.log(" How do you do " + this.name);
}, obj);
canOnlyFireOnce(); // Hello, Lonely Goose at the End of the World 
canOnlyFireOnce(); // nothing

Because fn = null sets the return function not null after it has been executed once, it will not be executed later. Then post a code shared by others on the Internet, which is the same as the reason:


function once(fn, context) { 
  var result;
 
  return function() { 
    if(fn) {
      result = fn.apply(context || this, arguments);
      fn = null;
    }
 
    return result;
  };
}
 
// Usage
var canOnlyFireOnce = once(function() {
  console.log('Fired!');
});
 
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nothing

The above is for everyone to organize javascript to execute only 1 function example, you can refer to the need.


Related articles: