4

I took the following function from this site and plugged it into my code to display a user-friendly time string based on a millisecond argument.

Why does this function not work?

    function getTimeFromMillis(millis)
    {

        milliSecs = millis;

        msSecs = (1000)
        msMins = (msSecs * 60)
        msHours = (msMins * 60)
        numHours = Math.floor(milliSecs/msHours)
        numMins = Math.floor((milliSecs - (numHours * msHours)) / msMins)
        numSecs = Math.floor((milliSecs - (numHours * msHours) - (numMins * msMins))/ msSecs)


        if (numSecs < 10){
          numSecs = "0" + numSecs.toString
        }
        if (numMins < 10){
          numMins = "0" + numMins.toString
        }

        resultString = numHours + ":" + numMins + ":" + numSecs     
        return resultString;

    }

If I pass it a millisecond value from my calling function I get this:

0:0function toString() { [native code] }:0function toString() { [native code] }

1 Answer 1

11

You forgot the () in your calls to "toString".

edit — sorry had to step away for a sec. As @Gareth commented, the references to "toString" are syntactically valid, as they're just references to functions. Thus the parser has no problems with your code. What goes wrong is when you implicitly convert those references to strings.

If you just add () to each call, it should work a lot better. Or, as that very page you linked to points out a few posts further down, you really don't need .toString() at all.

Sign up to request clarification or add additional context in comments.

1 Comment

Specifically, the code "0" + numMins.toString is adding a string to a function. Javascript does this by converting the function into a string, which it does by outputting the source of the function (or, the cryptic [native code] for built-in functions)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.