Javascript Browser Window setInterval() Method

Introduction

Alert "Hello" every 3 seconds, 3000 milliseconds:

setInterval(function(){ alert("Hello"); }, 3000);

Click the button to wait 3 seconds, then alert "Hello".

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/*from  w  ww .jav  a2 s .co  m*/
  setInterval(function(){ alert("Hello"); }, 3000);
}
</script>

</body>
</html>

The setInterval() method calls a function an expression at specified intervals in milliseconds.

The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.

The ID value returned by setInterval() is used as the parameter for the clearInterval() method.

To execute a function only once, after a specified number of milliseconds, use the setTimeout() method.

setInterval(function, milliseconds,param1, param2, ... );

Parameter Values

Parameter Description
functionRequired. The function that will be executed
millisecondsRequired. The intervals in milliseconds on how often to execute the code. If the value is less than 10, the value 10 is used
param1, param2, ... Optional. Additional parameters to pass to the function

The setInterval() method returns a Number representing the ID value of the timer that is set.

Use this value with the clearInterval() method to cancel the timer




PreviousNext

Related