codersx-javascript-basic

setTimeout và clearTimeout


1. Tìm hiểu setTimeout

1.1 Chức năng

1.2 Cấu trúc

setTimeout(fn,countTimer)

- `countTimer`: Khoảng thời gian chờ đếm ngược, đơn vị tính ms(miliseconds)
- `fn`: Hàm khối lệnh thực hiện sau khi countTimer đếm về 0.

1.3 Ví dụ 1

setTimeout(() => {
  console.log('Hello!');
}, 1000);
let logHello = () => console.log('Hello!');
setTimeout(logHello, 1000);
let logHello = (str) => console.log(str);
setTimeout(() => logHello('Hello!'), 1000);

1.4 Ví dụ 2

console.log('Begin');
console.log('End');
setTimeout(() => {
  console.log('Finish!');
}, 3000);

2. Tìm hiểu clearTimeout

1.1 Chức năng

1.2 Cấu trúc

clearTimeout(setTimeoutID)

- Cần xác định ID của khối lệnh setTimeout đang chạy ngầm.

1.3 Ví dụ

console.log('Begin');
console.log('End');
var logID = setTimeout(() => {
  console.log('Finish!');
}, 3000);

clearTimeout(logID);
console.log('Begin');
console.log('End');
var logID = setTimeout(() => {
  console.log('Finish!');
}, 3000);

clearImmediate(logID);

3. Bài tập

3.1 Bài tập 1

/**
 * Tạo 1 hàm doAfter nhận vào 2 tham số:
 *  - Tham số thứ 1: 1 function
 *  - Tham số thứ 2: Thời gian x (ms)
 * Hàm này sẽ gọi function sau 1 khoảng thời gian x ms
 */

3.2 Bài tập 2

/**
 * Tạo 1 hàm doAfter nhận vào 2 tham số:
 *  - Tham số thứ 1: 1 function
 *  - Tham số thứ 2: Thời gian x (ms)
 * Hàm này sẽ gọi function sau 1 khoảng thời gian x ms VÀ trả về 1 promise để có thể gọi như sau
 */
function doAfter() {}

function sayHello() {
  console.log('Hello');
}

function sayGoodbye() {
  console.log('Goodbye');
}

doAfter(sayHello, 1000).then(sayGoodbye);
// Expect:
// Đợi 1s
// Hello
// Goodbye