function displayTime () { var element = document.getElementById ("time"); element.innerHTML = Date(); return; } setInterval ('displayTime()', 100); The current time is: "> function displayTime () { var element = document.getElementById ("time"); element.innerHTML = Date(); return; } setInterval ('displayTime()', 100); The current time is: ">

Presentation is loading. Please wait.

Presentation is loading. Please wait.

setInterval window.setInterval (statement, interval);

Similar presentations


Presentation on theme: "setInterval window.setInterval (statement, interval);"— Presentation transcript:

1 setInterval window.setInterval (statement, interval);
Schedules a "statement" to occur every interval milliseconds (1000 milliseconds = 1 second) Statement is often a call to a function (built-in or user-defined)

2 Do Now: clock.html <script type="text/javascript">
function displayTime () { var element = document.getElementById ("time"); element.innerHTML = Date(); return; } setInterval ('displayTime()', 100); </script> <body> The current time is: <span id="time"></span> </body>

3 cancelling a timer Timers are actually objects.
Can hold the timer information in a variable: var t; // global variable for timer t =setInterval ('displayTime()', 50); </script> <button onclick="clearInterval (t)">Cancel</button>

4 Create a webpage named countdown.html with:
a div element with an id = "countdown" A global variable timeLeft and 3 functions: startCountdown () { prompt user for number of seconds set the global variable timeLeft to that many seconds call setInterval to call countDown() every second countDown () { display the time remaining in the countdown div reduce timeLeft by 1 if timeLeft equals 0, alert "Boom" and cancel timer cancelCountdown () { alert "Cancelled" and cancel timer 2 buttons - one to start and once to cancel

5 Moving an object Create a div with id="ball"
Use CSS to give the div a distinct background, a position: absolute, top: 50px, left: 0px, and a fixed height and width Create a global variable to keep track of the left position Use setInterval to periodically change the div element's left position (will make it move)

6 <div id="ball"></div>
<script type="text/javascript"> var left = 0; function moveBall () { var e = document.getElementById ("ball"); e.style.left = left + "px"; left = left + 1; } setInterval ("moveBall()", 100); </script>

7 Additional tasks Give the "ball" an image
use an <img> tag inside the bouncing div Make the ball "bounce" back and forth when left exceeds the right edge, start subtracting instead of adding to it Add a button to stop/start the ball Add a button to prompt the user for the speed


Download ppt "setInterval window.setInterval (statement, interval);"

Similar presentations


Ads by Google