Rafee Rafee - 8 months ago 47
Javascript Question

Cannot call a function inside another function javascript

<script src="https://raw.githubusercontent.com/mckamey/countdownjs/master/countdown.js"></script>

<script> function getAge (date) { k = countdown(date); } </script>

And it throws an error

countdown is not defined


I downloaded the file to local and, when i tried calling directly it works but doesn't when inside a function.

Answer Source

I don't get "countdown is not defined", I get "date is not defined". Now that I've had a chance to review the countdown.js file, You are not sending all the parameters to the function:

function countdown(start, end, units, max, digits) {
    var callback;

    // ensure some units or use defaults
    units = +units || DEFAULTS;
    // max must be positive
    max = (max > 0) ? max : NaN;

First, you need to define "date" or use "new Date()". Second, there are other parameters that need to be set, including the callback and target element to update. I'd suggest reading the documentation here.

Here's the sample from the readme file:

var timerId =
    new Date(),
    function(ts) {
      document.getElementById('pageTimer').innerHTML = ts.toHTML("strong");

// later on this timer may be stopped

Finally, you are not actually calling the getAge function anywhere that I can see. You have only defined it. If you run:

getAge(new Date());

You'll get no errors, but it will do nothing, because you have not defined any of the other parameters.