Convert seconds to hours, minutes and seconds (JavaScript)

This is JavaScript implementation of the PHP function previously described in Convert seconds to hours, minutes and seconds (PHP). Please see the link for more detailed explanation of the function.

  1. /**
  2.  * Convert number of seconds into time object
  3.  *
  4.  * @param integer secs Number of seconds to convert
  5.  * @return object
  6.  */
  7. function secondsToTime(secs)
  8. {
  9.     var hours = Math.floor(secs / (60 * 60));
  10.    
  11.     var divisor_for_minutes = secs % (60 * 60);
  12.     var minutes = Math.floor(divisor_for_minutes / 60);
  13.  
  14.     var divisor_for_seconds = divisor_for_minutes % 60;
  15.     var seconds = Math.ceil(divisor_for_seconds);
  16.    
  17.     var obj = {
  18.         "h": hours,
  19.         "m": minutes,
  20.         "s": seconds
  21.     };
  22.     return obj;
  23. }



출처 - http://codeaid.net/javascript/convert-seconds-to-hours-minutes-and-seconds-(javascript)

Posted by linuxism
,


Find angle between hour and minute hands in an analog clock


I was given this interview question recently:

Given a 12-hour analog clock, compute in degree the smaller angle between the hour and minute hands. Be as precise as you can.

I'm wondering what's the simplest, most readable, most precise algorithm is. Solution in any language is welcome (but do explain it a bit if you think it's necessary).

share|improve this question
8 
simplest? looking it up on wiki! : en.wikipedia.org/wiki/Clock_angle_problem'; –  Mitch Wheat May 1 '10 at 5:12
3 
I think that this is a purely mathematical problem, and also fairly trivial. I do not see how this question can get four up-votes... –  Andreas Rejbrand May 1 '10 at 12:06
add comment

It turns out that Wikipedia does have the best answer.

// h = 1..12, m = 0..59
static double angle(int h, int m) {
    double hAngle = 0.5D * (h * 60 + m);
    double mAngle = 6 * m;
    double angle = Math.abs(hAngle - mAngle);
    angle = Math.min(angle, 360 - angle);
    return angle;
}

Basically:

  • The hour hand moves at the rate of 0.5 degrees per minute
  • The minute hand moves at the rate of of 6 degrees per minute

Problem solved.


And precision isn't a concern because the fractional part is either .0 or .5, and in the range of 0..360, all of these values are exactly representable in double.

share|improve this answer
1 
This is not quite correct for h >= 12. –  starblue May 1 '10 at 11:03
1 
@starblue: I've clarified that it's a 12-hour analog clock. –  polygenelubricants May 1 '10 at 11:34 
7 
@starblue Can analog clock be ever 24hr? –  AksharRoop Sep 3 '12 at 8:20
add comment

For finding the angle between the hands of a clock is ,

30 * [HRS - (MIN/5)] + (MIN/2) 
share|improve this answer
   
This works great. Thanks for the answer!! –  gabhi Nov 3 '13 at 18:46
   
Missing absolute value ? –  Hunter McMillen Dec 17 '13 at 14:27
add comment

The java code that polygenlubricants is similar than mine. Let's assume that the clock is 12 hour instead of 24.

If it's 24 hours, then that's a different story. Also, another assumption, assume if the clock is stopped while we calculate this.

One clock cycle is 360 degree.

  1. How many degree can the minute hand run per minute? 360 / 60 = 6 degree per minute.

  2. How many degree can the hour hand run per hour? 360/12 = 30 degree per hour (since hour hand run slower than minute)

Since it's easier to calculate in the unit, "minute", let's get

"how many degree can the hour hand run per minute"?

30 / 60 = 0.5 degree per minute.

So, if you know how to get those numbers, the problem is pretty much done with solution.

share|improve this answer
add comment

Try this code :

import java.util.Scanner;

class Clock{

    public static void main(String args[]){
        int hours,mins;

    System.out.println("Enter the Time(hours) : ");
        Scanner dx = new Scanner(System.in);
        hours = dx.nextInt();

    System.out.println("Enter the time(mins) : ");
        Scanner fx = new Scanner(System.in);
        mins = fx.nextInt();

    if(hours>=0 && hours<=12){

        if(mins>=0 && mins<=59){
            double hDegrees = (hours * 30) + (mins * 0.5);
                    double mDegrees = mins * 6;
                    double diff  = Math.abs(hDegrees - mDegrees);

        System.out.println("The angle between sticks is (degrees) : "+diff);
                if (diff > 180){ 

                diff = 360 - diff;
        System.out.println("The angle between sticks is (degrees) : "+diff);
                }

        }

    }

    else{
        System.out.println("Wrong input ");
    }


}

}
share|improve this answer
add comment

for finding the angle between the hour hand and the minute hand is

angle=(hour*5-min)*6
share|improve this answer
add comment

I tried to solve this problem but I don't think it can be solved mathematics.

share|improve this answer
add comment

I do not know if it's right, .something like this?

//m*360/60 - (h*360/24)+(m*360/(24*60)) ->
t = abs(25*m - 60*h)/4
t = min(t,360-t)
share|improve this answer
   
Well it can't be right if you're missing an end parenthesis :D –  Wallacoloo May 1 '10 at 5:17
   
For h=3m=0, I get 45. It should be 90. –  polygenelubricants May 1 '10 at 5:37
   
@poly okay, I forgot regular clock is 12, not 24 hours. if you replace division by 24 with 12, you should get correct –  Anycorn May 1 '10 at 5:42




출처 - http://stackoverflow.com/questions/2748965/fnd-angle-between-hour-and-minute-hands-in-an-analog-clock



'Development > JavaScript' 카테고리의 다른 글

javascript - requestAnimationFrame  (0) 2014.04.02
javascript - 초에서 시간, 분 구하기  (0) 2014.04.01
javascript - iife setTimeout  (0) 2014.04.01
javascript - window.JSON 객체  (0) 2014.03.27
javascript - DocumentFragment  (0) 2014.02.01
Posted by linuxism
,


A Recursive setTimeout Pattern

Monday, October 18, 2010

Colin Snover wrote a good article about why he thinks setInterval is considered harmful:

  1. setInterval ignores errors. If an error occurs in part of your code, it'll be thrown over and over again.
  2. setInterval does not care about network latency. When continuously polling a remote server for new data, the response could take longer than the interval amount, resulting in a bunch of queued up AJAX calls and an out-of-order DOM.

The solution is to recursively call a named function within setTimeout, which guarantees that your logic has completed before attempting to call it again. At such, this also doesn't guarantee that your logic will occur on a regular interval. If you want new data every 10 seconds and it takes 15 for your response to come back, you're now behind by 5 seconds. Colin notes that you can adjust your delay if need be, but you shouldn't really care as JavaScript timers are not accurate to begin with.

So how to do this? Consider an AJAX poller as this is a common use case:

// old and busted - don't do this
setInterval(function(){
   $.ajax({
       url: 'foo.htm',
       success: function( response ){
          // do something with the response
       }
   });
}, 5000);

// new hotness
(function loopsiloop(){
   setTimeout(function(){
       $.ajax({
           url: 'foo.htm',
           success: function( response ){
               // do something with the response

               loopsiloop(); // recurse
           },
           error: function(){
               // do some error handling.  you
               // should probably adjust the timeout
               // here.

               loopsiloop(); // recurse, if you'd like.
           }
       });
   }, 5000);
})();

I'm doing three things here:

  1. Declaring a function loopsiloop that is immediately invoked (notice the parens at the end).
  2. Declaring a timeout handler to fire after 5 seconds.
  3. Polling the server inside the timeout, which upon either success/failure will call loopsiloop and continue the poll.

It's also important to remember that DOM manipulation takes time as well. With this pattern we're guaranteed that the response will be back from the server AND the DOM will be loaded with new content before attempting to request more data.

It's wise to add error handling in cases when the server experiences latency issues or becomes unresponsive. When requests fail, try increasing the polling interval to give the server some breathing room, and only recurse when under a fixed amount of failed attempts:

// keep track of how many requests failed
var failed = 0; 

(function loopsiloop( interval ){
   interval = interval || 5000; // default polling to 1 second

   setTimeout(function(){
       $.ajax({
           url: 'foo.htm',
           success: function( response ){
               // do something with the response

               loopsiloop(); // recurse
           },
           error: function(){

               // only recurse while there's less than 10 failed requests.
               // otherwise the server might be down or is experiencing issues.
               if( ++failed < 10 ){

                   // give the server some breathing room by
                   // increasing the interval
                   interval = interval + 1000;
                   loopsiloop( interval );
               }
           }
       });
   }, interval);
})();

But the success handler can still fire even if the response is an error, the astute reader might say. For that, let's break out the error logic from its handler so it can also be used in the success callback:

// keep track of how many requests failed
var failed = 0, interval = 5000; 

function errorHandler(){
   if( ++failed < 10 ){

       // give the server some breathing room by
       // increasing the interval
       interval = interval + 5000;
       loopsiloop( interval );
   }
}

(function loopsiloop( interval ){
   setTimeout(function(){
       $.ajax({
           url: 'foo.htm',
           success: function( response ){

               // what you consider valid is totally up to you
               if( response === "failure" ){
                   errorHandler();
               }
           },
           error: errorHandler
       });
   }, interval);
})();

Good, except that now we have a bunch of floating variables and functions. Ugly, amirate? Let's organize this into an object literal:

var poller = {

   // number of failed requests
   failed: 0,

   // starting interval - 5 seconds
   interval: 5000,

   // kicks off the setTimeout
   init: function(){
       setTimeout(
           $.proxy(this.getData, this), // ensures 'this' is the poller obj inside getData, not the window object
           this.interval
       );
   },

   // get AJAX data + respond to it
   getData: function(){
       var self = this;

       $.ajax({
           url: 'foo.htm',
           success: function( response ){

               // what you consider valid is totally up to you
               if( response === "failure" ){
                   self.errorHandler();
               } else {
                   // recurse on success
                   self.init();
               }
           },

           // 'this' inside the handler won't be this poller object
           // unless we proxy it.  you could also set the 'context'
           // property of $.ajax.
           error: $.proxy(self.errorHandler, self)
       });
   },

   // handle errors
   errorHandler: function(){
       if( ++this.failed < 10 ){

           // give the server some breathing room by
           // increasing the interval
          this.interval += 1000;

          // recurse
          this.init();
       }
   }
};

// kick this thing off
poller.init();

And there you have it – a safe, basic, and organized AJAX poller to get you started.



출처 - http://www.erichynds.com/blog/a-recursive-settimeout-pattern







Posted by linuxism
,