Open In App

D3.js interval() Function

The d3.interval() function is used to call the function after every given time interval or delay. If the delay is not given then the delay is equal to the timer.

Syntax:



d3.interval(callback, delay);

Parameters: It takes the two parameters as mentioned above and described below:

Returns: It returns an object.



Note: The output may be different every time the code is executed.

Example 1: When no delay is given.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <style>
        .originalColor {
            height: 100px;
            width: 100px;
        }
  
        .darkerColor {
            height: 100px;
            width: 100px;
        }
    </style>
</head>
  
<body>
    <!-- Fetching from CDN of D3.js -->
    <script type="text/javascript" 
        src="https://d3js.org/d3.v4.min.js">
    </script>
      
    <script>
        let count = 0;
        let func = function (e) {
            count++;
            console.log(e);
            console.log("Time interval will "
                + "stop when count is greater 5" 
                + "current count: ", count);
            if (count > 5)
                timer.stop()
        }
        var timer = d3.interval(func);
    </script>
</body>
  
</html>

Output:

Example 2: When a delay is given.




<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <style>
        .originalColor {
            height: 100px;
            width: 100px;
        }
  
        .darkerColor {
            height: 100px;
            width: 100px;
        }
    </style>
</head>
  
<body>
    <!-- Fetching from CDN of D3.js -->
    <script type="text/javascript" 
        src="https://d3js.org/d3.v4.min.js">
    </script>
      
    <script>
        let count = 0;
        console.log("The delay is 500ms.");
        let func = function (e) {
            count++;
            console.log(e);
            console.log("Time interval will "
                + "stop when count is greater 3" 
                + " current count: ", count);
            if (count > 3)
                timer.stop()
        }
        var timer = d3.interval(func, 500);
    </script>
</body>
  
</html>

Output:


Article Tags :