Home >Web Front-end >JS Tutorial >javascript 禁止重复调用只允许执行一次函数

javascript 禁止重复调用只允许执行一次函数

WBOY
WBOYOriginal
2016-06-01 09:54:522429browse
<code class="language-javascript">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(); // nada</code>

这个 once 函数能够保证你提供的函数只执行唯一的一次,防止重复执行。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn