💻 Dev

🛠️ 처음부터 만드는 Once — 함수를 정확히 한 번만 실행하기

언제 쓸까?


초기화 로직, 이벤트 리스너, 싱글톤 생성처럼 정확히 한 번만 실행되어야 하는 코드에 유용합니다.
```javascript
// ❌ 문제: 버튼 여러 번 클릭 시 함수가 매번 실행됨
button.addEventListener('click', initialize);
// ✅ Once 적용: 첫 번째 클릭만 실행, 이후는 무시
button.addEventListener('click', once(initialize));
```

기본 구현


```javascript
function once(fn) {
let called = false;
let result;
return function (...args) {
if (!called) {
called = true;
result = fn.apply(this, args);
}
return result;
};
}
// 테스트
const greet = once((name) => {
console.log(`Hello, ${name}!`);
return `Greeted ${name}`;
});
greet('Alice'); // "Hello, Alice!" 출력
greet('Bob'); // 실행 안 됨
greet('Charlie'); // 실행 안 됨
```

실전 예제: 초기화 로직


```typescript
class Database {
private static instance: Database | null = null;
private initialized = false;
private constructor() {}
// 초기화를 정확히 한 번만 실행
private init = once(async () => {
await this.connect();
this.initialized = true;
});
async connect() {
console.log('DB 연결 중...');
return new Promise(r => setTimeout(r, 1000));
}
static getInstance() {
if (!this.instance) {
this.instance = new Database();
}
return this.instance;
}
}
// 여러 번 호출해도 초기화는 한 번만
await Database.getInstance().init();
await Database.getInstance().init();
```

고급: 에러 처리


```javascript
function onceWithError(fn) {
let called = false;
let result;
let error;
return function (...args) {
if (!called) {
called = true;
try {
result = fn.apply(this, args);
} catch (e) {
error = e;
called = false; // 실패하면 다음 호출에 재시도
throw e;
}
}
if (error) throw error;
return result;
};
}
```

참고


  • [Lodash _.once](https://lodash.com/docs/#once)

  • [MDN: 함수형 프로그래밍 패턴](https://developer.mozilla.org/en-US/docs/Glossary/Functional_programming)
  • 💬 0
    👁 0 views

    Comments (0)

    💬

    No comments yet.

    Be the first to comment!