-
Notifications
You must be signed in to change notification settings - Fork 1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
实现一个 once 函数, 传入函数参数只执行一次 #17
Labels
Comments
朴实无华版function once(fn) {
let _window = window;
if (!_window.onceSet) {
_window.onceSet = new Set();
}
if (!_window.onceSet.has(fn)) {
fn();
_window.onceSet.add(fn);
}
}
const fn = () => {
console.log("hi");
};
once(fn);
once(fn); |
卧槽卧槽!简直神之一手啊! |
Closed
简单直接const onceSet = new Set();
const once = (fn) => {
if (!onceSet.has(fn) && onceSet.add(fn)) fn?.()
};
const fn = () => {
console.log("hi");
};
once(fn);
once(fn);
once(fn); |
可以实现,但是多了一个污染变量,还可以优化~ |
勉强实现function once(fn) {
if (!once.execute) {
fn()
once.execute = true
}
}
const foo = () => console.log('once')
once(foo)
once(foo) |
闭包版function before(n, func) {
let result
if (typeof func !== 'function') {
throw new TypeError('Expected a function')
}
return function(...args) {
if (--n > 0) {
result = func.apply(this, args)
}
if (n <= 1) {
func = undefined
}
console.log('result', result);
return result
}
}
function once(func) {
return before(2, func)
}
const res = once((arg) => arg);
console.log('once', res(10));
console.log('once', res(2)); |
function once(fn, maxExec = 1) {
let onceFn = () => {
if(maxExec === 0) return
maxExec--
fn()
}
return onceFn
}
const a = once(() => console.log(1324), 2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The text was updated successfully, but these errors were encountered: