Thursday 7 April 2016

timer in javascript

//Timer related code snippets in js
console.log(new Date().getSeconds()); //e.g., 49 seconds
/* function setTimeout() is a global object window and we do not need to prefix it with window.*/
setTimeout(function() {
  console.log(new Date().getSeconds());
 }, 1000
);/* 1000 milliseconds of delay should be observed before calling the function setTimeout after the internal function has been called. */
/* I got 
6
7
because there were 6 seconds in to the minute and then it was 7 seconds into the minute. Note that the 7 appears after an 
interval of 1 second after the 6 appears on the console. If I delete the ', 1000' then I will 
instead get
6
6
as no delay is being observed. 
*/

//*******************************************************
console.log(new Date().getSeconds());
/* Assigning the id of the timer to a variable so that we use that id later on to clear the timer and prevent it from being activated. */
var id = setTimeout(function(){
  console.log(new Date().getSeconds());
 }, 1000
);
clearTimeout(id);
/* After executing the code above we get only one number as our timer is prevented being activated by the clearTimeout() method.
*/
//*******************************************************
/* In the code snippet given below we pass a funciton to method setInterval() and that internal function will be called over and 
over again untill the if condition is true and it is then when the function clearInterval(id) will be called to stop calling the 
internal function.
*/
console.log(new Date().getSeconds());
var id = setInterval(function(){
  var seconds = new Date().getSeconds();
        console.log(seconds);
        if(seconds === 30)//shutting down the timer when there are 30 seconds into the minute
         clearInterval(id);//id exists in the outer function.
 }, 1000
);
//*******************************************************


No comments:

Post a Comment