在我们日常开发的时候,经常会碰到一种这样的情况:想让某个函数只执行一次,特别是在一些循环或定时执行的时候。
废话不多说,直接上代码:
function runonce(fn, context) { //控制让函数只触发一次
return function () {
try {
fn.apply(context || this, arguments);
}
catch (e) {
console.error(e);//一般可以注释掉这行
}
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 = "张三";
var canonlyFireOnce = runonce(function () {
console.log("你好" + this.name);
});
canonlyFireOnce(); //你好张三
canonlyFireOnce(); // nothing
// Usage 3:
var obj = {name: "天涯孤雁", age: 24};
var canonlyFireOnce = runonce(function () {
console.log("你好" + this.name);
}, obj);
canonlyFireOnce(); //你好天涯孤雁
canonlyFireOnce(); // nothing
因为返回函数执行一次后,fn = null将其设置未null,所以后面就不会执行了。再贴一个网上别人分享的代码,道理一样的:
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
以上就是为大家整理让javascript只执行一次的函数示例,有需要的可以参考。



