Skip to content
Advertisement

Taking a stab at a Javascript Timer and failing

JavaScript

The simple application crashes when I click the startBtn by indicating that displaySecs is null. I watched several tutorial and tried to create my own custom timer. Are there too many if statements? Is there a simpler cleaner way to do this?

Advertisement

Answer

this way:

JavaScript
JavaScript

following the PO’s comments for a request for additional explanation on:

JavaScript

this is like

JavaScript

(seconds < 10)?'0':'' is Conditional (ternary) operator
it is like this function :

JavaScript

Nb: your code use an oposite test if(seconds > 9) == if the value is greather than 9. I believe I read somewhere that testing if an integer is less than 10 requires less cycle for the processor than testing if it is supper to 9 – this needs to be verified (but it’s not very important, it’s just a matter of habit).
.

if my code was without parentheses before the + seconds as:

JavaScript

it would be interpreted as follows:

JavaScript

and would just output the character zero for all values less than 10 (zero through nine) – which would be an error

so I have to precise the order of imperetation with correct parentheses:

JavaScript

hope this explanation will help you?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement