Javascript setTimeout ()

Trong hướng dẫn này, bạn sẽ tìm hiểu về phương thức JavaScript setTimeout () với sự trợ giúp của các ví dụ.

Các setTimeout()phương pháp thực hiện một khối mã sau thời gian quy định. Phương thức này chỉ thực thi mã một lần.

Cú pháp thường được sử dụng của JavaScript setTimeout là:

 setTimeout(function, milliseconds);

Các thông số của nó là:

  • function - một hàm chứa một khối mã
  • mili giây - thời gian mà sau đó hàm được thực thi

Các setTimeout()phương thức trả về một intervalID , mà là một số nguyên dương.

Ví dụ 1: Hiển thị văn bản một lần sau 3 giây

 // program to display a text using setTimeout method function greet() ( console.log('Hello world'); ) setTimeout(greet, 3000); console.log('This message is shown first');

Đầu ra

Tin nhắn này được hiển thị đầu tiên  Xin chào thế giới

Trong chương trình trên, setTimeout()phương thức này gọi greet()hàm sau 3000 mili giây ( 3 giây).

Do đó, chương trình chỉ hiển thị dòng chữ Hello world một lần sau 3 giây.

Lưu ý : setTimeout()Phương pháp này hữu ích khi bạn muốn thực thi một khối một lần sau một thời gian. Ví dụ: hiển thị một tin nhắn cho người dùng sau thời gian được chỉ định.

Các setTimeout()phương thức trả về id khoảng. Ví dụ,

 // program to display a text using setTimeout method function greet() ( console.log('Hello world'); ) let intervalId = setTimeout(greet, 3000); console.log('Id: ' + intervalId); 

Đầu ra

 Id: 3 Hello world

Ví dụ 2: Thời gian hiển thị 3 giây một lần

 // program to display time every 3 seconds function showTime() ( // return new date and time let dateTime= new Date(); // returns the current local time let time = dateTime.toLocaleTimeString(); console.log(time) // display the time after 3 seconds setTimeout(showTime, 3000); ) // calling the function showTime();

Đầu ra

 5:45:39 CH 5:45:43 CH 5:45:47 CH 5:45:50 CH… 

Chương trình trên hiển thị thời gian sau mỗi 3 giây.

Các setTimeout()phương pháp gọi hàm chỉ một lần sau khi khoảng thời gian (ở đây 3 giây).

Tuy nhiên, trong chương trình trên, do hàm đang gọi chính nó nên chương trình sẽ hiển thị thời gian sau mỗi 3 giây.

Chương trình này chạy vô thời hạn (cho đến khi hết bộ nhớ).

Lưu ý : Nếu bạn cần thực thi một hàm nhiều lần, tốt hơn nên sử dụng setInterval()phương pháp này.

JavaScript clearTimeout ()

Như bạn đã thấy trong ví dụ trên, chương trình thực thi một khối mã sau khoảng thời gian được chỉ định. Nếu bạn muốn dừng lệnh gọi hàm này, bạn có thể sử dụng clearTimeout()phương pháp.

Cú pháp của clearTimeout()phương thức là:

 clearTimeout(intervalID);

Đây intervalIDlà giá trị trả về của setTimeout()phương thức.

Ví dụ 3: Sử dụng phương thức clearTimeout ()

 // program to stop the setTimeout() method let count = 0; // function creation function increaseCount()( // increasing the count by 1 count += 1; console.log(count) ) let id = setTimeout(increaseCount, 3000); // clearTimeout clearTimeout(id); console.log('setTimeout is stopped.');

Đầu ra

 setTimeout bị dừng.

In the above program, the setTimeout() method is used to increase the value of count after 3 seconds. However, the clearTimeout() method stops the function call of the setTimeout() method. Hence, the count value is not increased.

Note: You generally use the clearTimeout() method when you need to cancel the setTimeout() method call before it happens.

You can also pass additional arguments to the setTimeout() method. The syntax is:

 setTimeout(function, milliseconds, parameter1,… .paramenterN);

When you pass additional parameters to the setTimeout() method, these parameters (parameter1, parameter2, etc.) will be passed to the specified function.

For example,

 // program to display a name function greet(name, lastName) ( console.log('Hello' + ' ' + name + ' ' + lastName); ) // passing argument to setTimeout setTimeout(greet, 1000, 'John', 'Doe');

Output

 Hello John Doe

Trong chương trình trên, hai tham số JohnDoeđược truyền cho setTimeout()phương thức. Hai tham số này là các đối số sẽ được truyền cho hàm (ở đây là greet()hàm) được định nghĩa bên trong setTimeout()phương thức.

Đề xuất Đọc: JavaScript async () và await ()

thú vị bài viết...