What is JS timing

0 votes
32 views
Ravi Vishwakarma asked 11 days ago in Web Application by Ravi Vishwakarma

What is JS timing    

1 Answer

1 votes
Ethan Karla answered 9 days ago by Ethan Karla
Programmers use timing events to delay the execution of certain code, or to repeat code at a specific interval. There are two native functions in the JavaScript library used to accomplish these tasks.
  1. setTimeout()
  2. setInterval().
setTimeout
setTimeout() is used to delay the execution of the passed function by a specified amount of time. There are two parameters that you pass to setTimeout(): the function you want to call, and the amount of time in milliseconds to delay the execution of the function. setTimeout() will execute the function from the first argument one time after the specified time has elapsed.
Syntax – setTimeout(function-name , millisecond)
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Timing</h2>
<p>Click 'Try it'. Wait 3 seconds, and the page will alert 'Hello'.</p>
<button onclick='setTimeout(myFunction, 3000);'>Try it</button>
<script>
function myFunction() {
  alert('Hello');
}
</script>
</body>
</html>
setInterval
Use setInterval() to specify a function to repeat with a time delay between executions. Again, two parameters are passed to setInterval(): the function you want to call, and the amount of time in milliseconds to delay each call of the function. setInterval() will continue to execute until it is cleared.
Syntax – setInterval (function-name , millisecond)
<!DOCTYPE html>
<html lang='en' xmlns='http://www.w3.org/1999/xhtml'>
<head>
    <meta charset='utf-8' />
    <title></title>
</head>
<body>
    <h2>JavaScript Timing</h2>
    <p>A script on this page starts this clock:</p>
    <p id='demo'></p>
    <script>
        function myTimer() {
          const d = new Date();
          document.getElementById('demo').innerHTML = d.toLocaleTimeString();
        }
        setInterval(myTimer, 1000);
    </script>
</body>
</html>