JavaScript JS Tutorial JS Objects JS Functions JS Classes JS Async JS HTML DOM JS Browser BOM JS Web APIs JS AJAX JS JSON JS vs jQuery JS Graphics



JS Timing

JavaScript Timing is a feature that allows developers to execute code at specific intervals or after a certain amount of time has passed. This feature is essential for creating dynamic and interactive web applications that respond to user input and update in real-time.

There are three main functions that are used for timing in JavaScript:

  • setTimeout()
  • setInterval()
  • requestAnimationFrame()

setTimeout()

The setTimeout() function is used to execute a piece of code after a specified amount of time has passed. The function takes two arguments: the first argument is the code to be executed, and the second argument is the time delay in milliseconds.

Here is an example of using setTimeout() to display an alert message after 5 seconds:

<script>
  setTimeout(function() {
    alert("Hello, world!");
  }, 5000);
</script>

setInterval()

The setInterval() function is used to execute a piece of code repeatedly at a specified interval. The function takes two arguments: the first argument is the code to be executed, and the second argument is the time delay in milliseconds.

Here is an example of using setInterval() to update the time every second:

<script>
  setInterval(function() {
    var date = new Date();
    document.getElementById("time").innerHTML = date.toLocaleTimeString();
  }, 1000);
</script>

<p>The current time is: <span id="time"></span></p>

requestAnimationFrame()

The requestAnimationFrame() function is used to execute a piece of code before the next repaint of the browser. This function is often used for animations and other visual effects.

Here is an example of using requestAnimationFrame() to animate a circle:

<canvas id="canvas" width="200" height="200"></canvas>

<script>
  var canvas = document.getElementById("canvas");
  var context = canvas.getContext("2d");
  var x = 100;
  var y = 100;
  var radius = 50;
  var speed = 2;

  function animate() {
    requestAnimationFrame(animate);
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.beginPath();
    context.arc(x, y, radius, 0, 2 * Math.PI);
    context.fill();
    x += speed;
    if (x + radius > canvas.width || x - radius < 0) {
      speed = -speed;
    }
  }

  animate();
</script>

JavaScript Timing is a powerful feature that allows developers to create dynamic and interactive web applications. By using functions like setTimeout(), setInterval(), and requestAnimationFrame(), developers can execute code at specific intervals or after a certain amount of time has passed.

References

Activity