JavaScript
setTimeout / clearTimeout
- 정해진 시간 후에 코드를 실행하는 함수다.
- 인수가 필요한 경우 3번째 인자로 넘겨준다.
clearTimeout
은 예정된 작업을 없앤다.setTimeout
은 타임 아이디를 반환하는데,clearTimeout
에 타임 아이디를 넘겨주면 예정된 스케쥴을 취소할 수 있다.delay
를 0으로 준다해도 코드가 바로 실행되지 않고 스케쥴에 추가가 되며, 스크립트가 종료된 후 예정된 스케쥴을 실행한다.- 브라우저는 기본적으로
4ms
의 대기시간이 있기 때문에 0이라고 작성해도4ms
혹은 그 이상의 시간이 걸린다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function fn() {
console.log("3초후 작성됩니다.");
}
setTimeout(fn, 3000);
setTimeout(function () {
console.log("3초후 작성됩니다.");
}, 3000);
// 인자
function hello(name) {
console.log(`안녕하세요 ${name}님.`);
}
setTimeout(hello, 3000, "아무개"); // 안녕하세요 아무개님.
setInterval
setTimeout
과 동일하게 작동되며 작업이 반복된다.
1
2
3
4
5
6
7
8
9
10
11
12
13
function consoleName(name) {
console.log(name);
}
const tId = setInterval(consoleName, 3000, "Mike"); // Mike Mike Mike
const num = 0;
function showTime() {
console.log(`실행 후 ${num++}가 지났습니다.`);
if (num > 5) clearInterval(tId);
}
const tId = setInterval(showTime, 1000);
call
- 모든 함수에서 사용할 수 있는 메서드로, 특정값으로 지정할 수 있다.
- 함수에
call
을 하고this
로 사용할 객체를 넘기면,해당 함수가 주어진 객체의 메서드인 것처럼 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const mike = {
name: "Mike",
};
function showName() {
console.log(this.name);
}
showName(); // ""
// 현재 실행 중인 showName의 this는 전역 객체를 가리키고
// window의 name 속성이 없기 때문에 빈 문자열을 나타낸다.
showName.call(mike); // Mike
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
update.call(mike, 1999, "singer");
console.log(mike);
// {name: "Mike", birthYear: 1999, occupation: "singer "}
// 첫 번째 매개변수는 this로 사용될 값이다.
// 두 번째 매개변수부터는 함수가 사용할 매개변수이다.
apply
- 함수 매개변수를 처리하는 방법을 제외하면
call
과 같다. call
은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만,apply
는 매개변수를 배열로 받는다.
1
2
3
4
5
6
7
8
9
10
11
12
const mike = {
name: "Mike",
};
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
update.call(mike, [1999, "singer"]);
console.log(mike);
// {name: "Mike", birthYear: 1999, occupation: "singer "}
apply
는 배열 매개변수를 함수 매개변수로 사용할 때 유용하다.- 만약 최솟값과 최댓값을 구하는 배열에서
max,min
을 사용할 경우, 배열을 풀어서 작성해야 한다.(배열은 NaN) - 두 번째 매개변수로 배열을 전달하면, 배열의 요소들을 차례대로 인수로 사용한다.
- 첫 번째 매개변수는
this
로 사용될 값이지만 필요에 따라 필요하지 않아서null
등의 아무 값이나 사용해도 된다.
1
2
3
4
5
6
7
8
const nums = [1, 2, 3, 4, 5];
let minNum = Math.min(...num); // 1
minNum = Math.min(num); // NaN
minNum = Math.min.apply(null, num); // 1
// Math.min.apply(null, [1,2,3,4,5])
minNum = Math.min.call(null, ...num); // 1
// Math.min.call(null, 1,2,3,4,5)
bind
- 함수의
this
값을 영구히 바꿀 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const mike = {
name: "Mike",
};
function update(birthYear, occupation) {
this.birthYear = birthYear;
this.occupation = occupation;
}
const updateMike = this.bind(mike);
// updateMike는 항상 mike를 this로 받는다.
const user = {
name: "Mike",
showName: function () {
console.log(`hello, ${this.name}`);
},
};
user.showName();
let fn = user.showName;
fn(); // hello,
// fn에 할당할 때 this를 잃어버려 Mike가 없다.
fn.call(user); // hello, Mike
fn.apply(user); // hello, Mike
let bindMike = fn.bind(mike);
bindMike(); // hello, Mike