In JavaScript, setting timers usually use two built-in functions: setTimeout() and setInterval(). They allow you to execute a function after a specified time delay or repeatedly execute a function at a certain interval. Below, I will explain how to use them in combination with actual project code examples.
1. setTimeout() — Delay execution of a function
setTimeout() is used to execute a function after the specified delay time. It will only be executed once.
grammar:
setTimeout(callback, delay, ...args);
- callback: The function to be executed.
- delay: Delay time in milliseconds (1000 milliseconds = 1 second).
- args: Optional parameter, passed to it when executing the callback function.
Example 1: Simple setTimeout example
Suppose you have a button, and a message will be displayed after clicking the button is delayed by 2 seconds.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>setTimeout Example</title> </head> <body> <button >Click me</button> <p style="display: none;">This is a delay message</p> <script> const button = ('clickButton'); const message = ('message'); ('click', function() { // The message will be displayed after 2 seconds delay setTimeout(function() { = 'block'; }, 2000); // 2000 milliseconds = 2 seconds }); </script> </body> </html>
How it works:
The click event is triggered when the user clicks a button.
setTimeout() After a delay of 2 seconds, an anonymous function is executed to display the message.
2. setInterval() — execute function repeatedly at regular intervals
setInterval() is used to execute a function repeatedly at a specified time interval.
grammar:
setInterval(callback, interval, ...args);
- callback: The function to be executed.
- interval: Time interval in milliseconds.
- args: Optional parameter, passed to the callback function.
Example 2: Simple setInterval example
Suppose you are developing a countdown timer that regularly updates the time on the page.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>setInterval Example</title> </head> <body> <div >10</div> <script> let countdown = 10; const timerElement = ('timer'); const intervalId = setInterval(function() { countdown -= 1; = countdown; // Clear the timer when the countdown is over if (countdown <= 0) { clearInterval(intervalId); alert('Time is here! '); } }, 1000); // Update once every second </script> </body> </html>
How it works:
setInterval() executes the callback function every 1 second (1000 milliseconds).
The callback function updates the countdown on the page and clearInterval() at the end of the countdown to prevent the timer from continuing execution.
3. Application examples in actual projects
Example 3: Debounce and Throttle processing user input
Timers are very important in front-end development, especially when processing user input. Two common techniques are anti-shake and throttling.
- Debounce: The operation is performed after the user stops input for a period of time.
- Throttle: The limiting function can only be executed once per unit time.
Anti-shake example
Suppose you are developing a search box that wants the user to enter before making a request after stopping input for 500 milliseconds.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Debounce Example</title> </head> <body> <input type="text" placeholder="Please enter search content"> <script> let timeoutId; const searchInput = ('searchInput'); ('input', function(event) { // Clear the previous timer every time you enter and reset the new timer clearTimeout(timeoutId); timeoutId = setTimeout(function() { ('Perform a search operation:', ); }, 500); // Search after 500 milliseconds }); </script> </body> </html>
How it works:
Each time the user enters, the last time timer (clearTimeout(timeoutId)) is cleared and a new timer is restarted.
If the user stops input within 500 milliseconds, the search operation will be triggered.
Throttle example
Suppose you are developing a page scroll event processor, but you want to limit the frequency of scroll events to avoid frequent callbacks causing performance problems.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Throttle Example</title> </head> <body> <div style="height: 2000px;">Scroll the page to view the effect</div> <script> let lastTime = 0; function handleScroll() { const now = new Date().getTime(); // Scrolling event is triggered every 200 milliseconds if (now - lastTime >= 200) { lastTime = now; ('The page is scrolling! '); } } ('scroll', handleScroll); </script> </body> </html>
How it works:
Each time the scroll event is fired, the handleScroll function checks whether it has exceeded 200 milliseconds since the last trigger.
If the condition is met, a callback is executed and the last execution time is updated. This ensures that scrolling events do not fire too often.
4. Clear the timer
Use clearTimeout() or clearInterval() to clear the timer that has been set.
- clearTimeout() is used to clear the timer set by setTimeout().
- clearInterval() is used to clear the timer set by setInterval().
Example 4: Clear the timer
const timeoutId = setTimeout(function() { ('This won't be executed'); }, 1000); clearTimeout(timeoutId); // Cancel the timer
Summarize
- setTimeout() is used to delay execution of one-time operations.
- setInterval() is used to perform repeated operations at a time.
In actual projects, timers can help us realize optimization technologies such as anti-shake and throttling, and improve application performance.
Clearing the timer is very important, especially in dynamic pages to avoid memory leaks or unnecessary operations.
Through the use of these timers, we can optimize the user experience and improve the performance of our application, especially when dealing with complex interactions and high-frequency operations.
The above is the detailed content of how to set timers in JavaScript. For more information about setting timers in JavaScript, please pay attention to my other related articles!