Javascript case statement. What am I missing here:

I have a working clock in Javascript here:

I’m trying to adapt that to a watch face. Note that the font I am using renders a character “XI” for “|” and such.

What is wrong with this:

const hours = (now.getHours() % 12 || 12);

  switch(hours) {
  case 1:
    hour = "1";
    break;  
  case 2:
    hour = "2";
    break;
  case 3:
    hour = "3";
    break;
  case 4:
    hour = "4";
    break;       
  case 5:
    hour = "5";
    break;
  case 6:
    hour = "6";
    break;
  case 7:
    hour = "7";
    break;  
  case 8:
   hour = "8";
   break;
  case 9:
   hour = "9";
    break;
  case 10:
    hour = "{";
    break;       
  case 11:
    hour = "|";
    break;
  case 12:
    hour = "}";
    break;      
  default:
    hour = "0";
} 

 const timeStr = hour;

// Draw time centered
let width = render.getTextWidth(timeStr, timeFont);
render.drawText(timeStr, timeFont, white,
    (render.width - width) / 2, timeY);

The log says:

[VERBOSE] xsHost.c:155: Found mod "pebble.moddable.tech"
[ERROR] xsPlatform.c:209: undefined
[ERROR] xsPlatform.c:217: fxAbort unhandled exception: get hour: undefined variable
[VERBOSE] xsHost.c:155: Found mod "pebble.moddable.tech"
[ERROR] ault_handling.c:98: App fault! {2cee2995-751e-4446-a63a-fa262a886b88} PC: 0x5 LR: ???
[ERROR] xsPlatform.c:209: undefined
[ERROR] xsPlatform.c:217: fxAbort unhandled exception: get hour: undefined variable
[ERROR] ault_handling.c:98: App fault! {2cee2995-751e-4446-a63a-fa262a886b88} PC: 0x5 LR: ???

I suspect I am not assigning hour correctly in this case statement for this system. Assuming I can even use a case statement as shown.

1 Like

Are you declaring the hour variable somewhere? it needs to be preexisting for the switch case to overwrite it

1 Like

It is not necessary in the Javascript that works on that web page referenced, but I see what you mean.

I put in var hour = 1; before the case statement and that seems to have fixed that. Good to know since I have two other case statements to put in for tens place minutes and ones place minutes.

Thanks.

1 Like

It is necessary to declare the variable before using it in JavaScript. Variables are undefined if not defined defore usage, which is why you’re seeing the “variable is undefined” error message in your logs.

1 Like

I understand the concept, but like I said the Javascript I used for the web page version does not require this. Not sure why there is a difference here. Maybe because the Javascript needs to be processed by the code that translates it into whatever the watch runs on?

The error logs don’t show line numbers for where in the .js file the error is but refer to lines in C code is it? “Line 155? There aren’t that many lines in what I wrote.”

1 Like

It will depend on the order that the code is executed in. Without the full source code it’s hard to tell why exactly it needs to be different

1 Like

Well, that worked out fine.

1 Like