When you press the start button in view, the time is saved in localstorage and the timer function is called. Since the timer function is continuously called every second with setTimeout, console is displayed as 1,2,3… by console.log (elapsed) ;.

The value is calculated by dividing 31536000 (seconds of a year) from the elapsed seconds to get the elapsed years from that elapsed time.

I want to solve is press the start button and check the output of console.log (year);After pressing the start button, the first 3,6,9 and multiples of 3 are displayed. 1,2,2,2,3,3,3 ... and so on. I would like to solve the problem that when I press the start button, a strange value appears even though 0,0,0,0 must be displayed from the beginning.

function timer () {
    now = new Date ();
    // Elapsed time (seconds)
    elapsed = parseInt ((now.getTime ()-localStorage.getItem ("time"))/1000);
    console.log (elapsed);
    year = parseInt (elapsed/31536000);
    console.log (year);
    if (localStorage.getItem ("time")) {
      var id = setTimeout ("repetition ()", 1000);

I thought that the numerical value (31536000) was too large to give an accurate value, so when dividing by 31536, it was calculated well and 0 has been output since the start button was pressed.

Also, instead of suddenly writing the year part in seconds, it is a formula for calculating the number of seconds in a year. If i rewrite it as year = parseInt (elapsed/365 * 24 * 60 * 60);1000 or more) was output irregularly.

I didn't know the cause at all. If i have a solution, please let me know.

  • Answer # 1

    The cause of this bug is the use ofparseInteven though the argument is numeric.

    parseInt takes a string as an argument.
    In JavaScript, if the value is close to zero, such as0.000000031709791983764586, it is converted to a string with an exponential notation such as3.1709791983764586e-8.
    So, for example,parseInt (1/31536000)becomesparseInt (3.1709791983764586e-8)andparseInt ("3.1709791983764586e-8")and finally3.

    Bugs can be solved by usingMath.floorinstead of


Related articles