728x90
setTimeout은 일정 시간 후 코드를 비동기적으로 실행하는 함수입니다.
setTimeout(() => {
...code
}, n)
위와 같은 모양을 가지며, code부분에 실행할 code가 들어가며, n부분에 일정 시간이 들어갑니다.
예제)
class
timeout;
func = () => {
this.timeout = setTimeout(() => {
this.setState({
state: "now",
message: "클릭",
result: [],
});
this.startTime = new Date();
}, Math.floor(Math.random() * 1000) + 2000);
}
hooks
const timeout = useRef(null);
func = () => {
timeout.current = setTimeout(() => {
setState("now");
setMessage("클릭");
setResult([]);
startTime.current = new Date();
}, Math.floor(Math.random() * 1000) + 2000);
}
timeout에 setTimeout을 대입하는 것은 setTimeout을 제어하기 위해서 이름이 필요하기 때문입니다.
그래서 timeout에 넣게되면 timeout을 통해서 해당 함수를 제어할 수 있습니다.
예제 코드는 state를 변경하는 내용입니다.
랜덤값 0.00 ~ 0.99 + 2 의 시간 후에 위의 코드가 실행됩니다.
clearTimeout(x) 는 setTimeout을 종료할 수 있습니다.
class
clearTimeout(this.timeout);
hooks
clearTimeout(timeout.current);
해당 게시글은 www.youtube.com/watch?v=V3QsSrldHqI&list=PLcqDmjxt30RtqbStQqk-eYMK8N-1SYIFn&index=1&ab_channel=ZeroChoTV 의 강의내용을 기반으로 공부한 내용을 정리한 글입니다.
'React' 카테고리의 다른 글
[React] 클래스 라이프사이클 (0) | 2020.11.09 |
---|---|
[React] 반응속도 테스트 (class, hooks) (0) | 2020.11.06 |
[React] 조건문, 삼항 연산자 (0) | 2020.11.06 |
[React] 성능 최적화, PureComponent, memo, shouldComponentUpdate, React dev tools (0) | 2020.11.05 |
[React] 배열값 변경, 렌더링 (0) | 2020.11.05 |