Current course:

Intervals

Description:

A "interval" simliar to a "timeout", but it continues to run until specifically told to stop.

The Code:

<head>
      <script type="text/javascript">
            var myInterval = "";
            function continuousAlert() {
                  clearInterval(myInterval);
                  setInterval('alert("TESTING")', 4000);
            }

            function stopAlert() {
                  clearInterval(myInterval);
                  alert("Continuous alert has been stopped");
            }

      </script>
</head>

<body>
      <a href="#" onmouseup="continuousAlert();">Start Continuous Alert</a>
</body>

Example:

Start Continuous Alert

Stop the Alert

Explanation:

First, we create a link, and give it an onmouseup state, which is triggered when the mouse button is let "up" (a click). (You can use any mouse event, we're just using mouseup as an example).

Then, we create a function to be called when the mouseup is triggered, and we call it "continuousAlert" (you can name it whatever you want).

The function calls javascripts interval with "setInterval", and passes two variables - the first is what you'd like to run, and the second is time (in milliseconds) between each time it calls it.

In this case, we have it call an alert (with "TESTING" as it's alert text), and we tell it to wait 4 seconds (4000 milliseconds) between alerts.

Before the functions, you'll see we've created a variable called "myInterval" - this is used to hold the "interval", which allows us to later "clear" (or stop) it. Without this variable, we would have no way to tell Javascript to stop the continuous alert boxes from popping up.


Other things to think about

With intervals, you can do many things: