setTimeout
The setTimeout
function is a built - in JavaScript function that can be used in TypeScript as well. It allows you to execute a function after a specified number of milliseconds. The basic syntax is as follows:
setTimeout(callback: () => void, delay: number);
callback
: A function that will be executed after the delay.delay
: The number of milliseconds to wait before executing the callback.async/await
Promises are a way to handle asynchronous operations in JavaScript and TypeScript. You can create a promise that resolves after a certain delay and use async/await
syntax to make the code more readable.
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
setTimeout
// Simple example of using setTimeout
function sayHello() {
console.log('Hello!');
}
// Execute sayHello after 2000 milliseconds (2 seconds)
setTimeout(sayHello, 2000);
// Using an arrow function
setTimeout(() => {
console.log('This message is delayed.');
}, 3000);
async/await
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function main() {
console.log('Before delay');
await delay(2000);
console.log('After delay');
}
main();
Throttling is a technique used to limit the rate at which a function can be called. For example, you might want to limit the number of times a search function is called when a user types in an input field.
function throttle(func: () => void, delay: number) {
let timer: NodeJS.Timeout | null = null;
return function() {
if (!timer) {
func();
timer = setTimeout(() => {
timer = null;
}, delay);
}
};
}
function search() {
console.log('Searching...');
}
const throttledSearch = throttle(search, 500);
// Simulate user input
document.addEventListener('keydown', throttledSearch);
You can use delay functions to simulate loading processes in a web application.
function simulateLoading() {
console.log('Loading started...');
setTimeout(() => {
console.log('Loading completed.');
}, 3000);
}
simulateLoading();
When using async/await
with delay functions, it’s important to handle errors properly.
function delay(ms: number): Promise<void> {
return new Promise((resolve, reject) => {
if (ms < 0) {
reject(new Error('Delay time cannot be negative.'));
}
setTimeout(resolve, ms);
});
}
async function main() {
try {
await delay(2000);
console.log('Delay completed successfully.');
} catch (error) {
console.error('Error:', error);
}
}
main();
Use descriptive function names and comments to make your code more readable. For example, instead of using an anonymous function inside setTimeout
, define a named function.
function showWelcomeMessage() {
console.log('Welcome to the application!');
}
setTimeout(showWelcomeMessage, 1500);
Delay functions in TypeScript are powerful tools for handling asynchronous operations and controlling the flow of your program. Whether you are using setTimeout
directly or leveraging promises and async/await
, understanding how to introduce delays can greatly enhance the user experience and the functionality of your applications. By following common and best practices, you can write more robust and maintainable code.