Tuesday, December 22, 2020

Timers

JavaScript defines setTimeout() and setInterval() functions; these functions are not standard, but are implemented by both browsers and server-side JavaScript engines

The setTimeout function

setTimeout() invokes a function after a specified number of milliseconds has elapsed

timeoutID = setTimeout(function[, delay]);
  • the function parameter specifies the function to be executed after the timer expires
  • the delay parameter specifies the interval, in milliseconds, after the timer expires
  • the arg1, arg2, ... optional parameters specify additional arguments passed to function when timer expires
  • the timeoutID returned value identifies the timer; pass this value to the clearTimeout() function to cancel the timeout
  • note: if delay parameter is omitted, the function will be called as soon as possible, when the JavaScript engine is idle
  • note: the setTimeout function returns immediately and does not wait for the interval to elapse before returning

Example: setTimeout invocations

setTimeout(() => { console.log("Three"); }, 1000);
setTimeout(() => { console.log("two"); }, 2000);
setTimeout(() => { console.log("one"); }, 3000); 
setTimeout(() => { console.log("go!"); }, 4000);

Example: using setTimeout() and clearTimeout() with Console API

HTML

<button id="setTmr"> SET Timer </button> 
<button id="cancelTmr"> CANCEL Timer </button>    

JavaScript

let timeoutID;
const create = (e) => {
  timeoutID = setTimeout(console.log, 2000, 'Hurry up!');   
};
const dismiss = (e) => {
  clearTimeout(timeoutID);
};
document.getElementById('setTmr').addEventListener('click', create);
document.getElementById('cancelTmr').addEventListener('click', dismiss);

The setInterval function

The setInterval() invokes a function repeatedly every time a specified number of milliseconds has elapsed

intervalID = setInterval(function[, delay [, arg1, arg2, ...]]);
  • the function parameter is the function to be executed every interval of time
  • the delay parameter is the interval, in milliseconds, the timer should wait for between executions
  • the arg1, arg2, ... optional parameters specify additional arguments passed to function when timer expires
  • the returned intervalID is a value which identifies the timer; pass this value to clearInterval() to cancel the interval

Example: using setInterval(), and clearInterval() with Console API

let counter = 0;
let string = "Hello-World";

// every second clear console and log the string
let intervalID = setInterval(() => {
  console.clear();
  console.log(string.substring(0, ++counter));
  if(counter === string.length)
    clearInterval(intervalID);    
}, 1000);

No comments:

Post a Comment