Timers

Frontend SELF EN
Level 37 , Lesson 3
Available

4.1 setTimeout Function

Timers in JavaScript let you perform certain actions at specified time intervals. The two main methods for working with timers are setTimeout() and setInterval(). They're used to run code with a delay or at regular intervals.

The setTimeout() method lets you execute a function once after a specified number of milliseconds. This is useful for delaying code execution.

Syntax:

    
      const timeoutID = setTimeout(callback, delay, ...args);
    
  

Where:

  • callback: the function to be executed
  • delay: the delay in milliseconds before the function is executed
  • args: additional arguments to pass to the callback function

Example of using setTimeout():

JavaScript
    
      // Function to be executed in 2 seconds
      function greet() {
        console.log('Hello, world!');
      }

      // Setting a timer
      const timeoutID = setTimeout(greet, 2000);
    
  

4.2 Canceling a setTimeout Timer

If you need to cancel the execution of a function scheduled with setTimeout(), you can use the clearTimeout() method:

JavaScript
    
      // Function to be executed in 2 seconds
      function greet() {
        console.log('Hello, world!');
      }

      // Setting a timer
      const timeoutID = setTimeout(greet, 2000);

      // Canceling the timer
      clearTimeout(timeoutID);
    
  

Example with additional arguments:

JavaScript
    
      // Function to be executed in 2 seconds with arguments
      function greet(name) {
        console.log(`Hello, ${name}!`);
      }

      // Setting a timer with argument
      const timeoutID = setTimeout(greet, 2000, 'Alice');
    
  

4.3 setInterval Function

The setInterval() method allows you to repeatedly execute a function at specified time intervals. This is useful for periodic execution of code.

Syntax:

    
      const intervalID = setInterval(callback, delay, ...args);
    
  

Where:

  • callback: the function to be executed
  • delay: the interval in milliseconds between calls to the function
  • args: additional arguments to pass to the callback function

Example of using setInterval:

JavaScript
    
      // Function to be executed every 2 seconds
      function greet() {
        console.log('Hello, world!');
      }

      // Setting an interval
      const intervalID = setInterval(greet, 2000);
    
  

4.4 Canceling a setInterval Interval

If you need to stop repeated execution of a function, you can use the clearInterval() method.

JavaScript
    
      // Function to be executed every 2 seconds
      function greet() {
        console.log('Hello, world!');
      }

      // Setting an interval
      const intervalID = setInterval(greet, 2000);

      // Canceling the interval in 10 seconds
      setTimeout(() => {
        clearInterval(intervalID);
        console.log('Interval cleared');
      }, 10000);
    
  

Example with additional arguments:

JavaScript
    
      // Function to be executed every 2 seconds with arguments
      function greet(name) {
        console.log(`Hello, ${name}!`);
      }

      // Setting an interval with argument
      const intervalID = setInterval(greet, 2000, 'Alice');
    
  

4.5 Practical Use Examples

Example 1: Auto-updating Time

HTML
    
      <!DOCTYPE html>
      <html>
        <head>
          <title>Auto-update Time</title>
        </head>
        <body>
          <h1>Current Time</h1>
          <div id="time"></div>

          <script>
            function updateTime() {
              const now = new Date();
              const timeString = now.toLocaleTimeString();
              document.getElementById('time').textContent = timeString;
            }

            // Update the time every second
            updateTime();
            setInterval(updateTime, 1000);
          </script>
        </body>
      </html>
    
  

Example 2: Periodic Data Request

JavaScript
    
      // Function to simulate data request
      function fetchData() {
        console.log('Fetching data...');
        // Here you can make a real request to the server
      }

      // Execute data request every 10 seconds
      const intervalID = setInterval(fetchData, 10000);

      // Stop requests in 1 minute
      setTimeout(() => {
        clearInterval(intervalID);
        console.log('Stopped fetching data');
      }, 60000);
    
  
1
Task
Frontend SELF EN, level 37, lesson 3
Locked
Delayed Message
Delayed Message
1
Task
Frontend SELF EN, level 37, lesson 3
Locked
Time Update
Time Update
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION