# Timing functions

method description
window.setTimeout(cb, <delay>) (opens new window) execute the callback function (cb) once after a fixed <delay> in ms
window.setInterval(cb, <delay>) (opens new window) execute the callback function (cb) repeatedly with a fixed <delay> in ms
window.clearInterval(<intervalId>) (opens new window) cancels an action that was established with setInterval()

REMARKS

  • The window prefix is optional and can be left out
  • setTimeout() is often used in examples to simulate a delay in the retrieval of external data
  • To use clearInterval(), you have to bind setInterval() to a variable first
let timer = setInterval(function () {
    // execute this code every 3 seconds
}, 3000);

document.getElementById('cancelTimer').addEventListener('click', function(e) {
    clearInterval(timer); // cancel the timer
});
1
2
3
4
5
6
7
  • setInterval() starts for the first time after <delay> ms
    • Use an external callback function to start the function immediately and then repeatedly after x ms
function cb() {
    // execute this code immediately and then every 3 seconds
}

cb(); // start cb() immediately
setInterval(cb, 3000);  // run cb() every 3 seconds

1
2
3
4
5
6
7

# Examples

# Analog + digital clock

  • Open es6/timing/clock.html and es6/timing/clock.js
  • The clock is written as an SVG image wich contains four elements that change over time
    • text#digitalTime shows the time with toLocaleTimeString() (opens new window)
    • line#sec rotates 6 degrees per second
    • line#min rotates 6 degrees per minute
    • line#hour rotates 30 degrees per hour + 0.5 degrees per minute

REMARK

  • Rotating SVG shapes differs from the CSS transform: rotate() method
    • An SVG rotation is defined as an attribute of the elements (line, rect, ...) within the <svg> tag:
      <line ... transform="rotate(angle, x-rotationPoint, y-rotationPoint)">
    • Besides the angle, also the rotation point can be specified

# Reaction test

  • Open es6/timing/reaction.html and es6/timing/reaction.js
Last Updated: 4/28/2021, 2:13:34 PM