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

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

WBOY
Release: 2016-06-01 09:54:52
Original
2445 people have browsed it
<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>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template