Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 138163

Function returning not defined when called from script file

$
0
0

After learning how to put all javascript code into a single page by declaring and calling functions like so:

function script() {
  const foo=document.querySelector('.foo');

  if(!foo) {
    return
  }

  code here....
}

script();

I am now getting an error:

ReferenceError: timer is not defined

The code works without any problem when run independent, but when nested within a function the timer is no longer defined. Here is the working code:

let upgradeTime = 535680;
let seconds = upgradeTime;

function timer() {
  let days = Math.floor(seconds / 24 / 60 / 60);
  let hoursLeft = Math.floor(seconds - days * 86400);
  let hours = Math.floor(hoursLeft / 3600);
  let minutesLeft = Math.floor(hoursLeft - hours * 3600);
  let minutes = Math.floor(minutesLeft / 60);
  let remainingSeconds = seconds % 60;

  function pad(n) {
    return n < 10 ? "0" + n : n;
  }
  document.getElementById("countdown").innerHTML = `${pad(days)}: ${pad(hours)}: ${pad(minutes)}: ${pad(remainingSeconds)}`;
  if (seconds == 0) {
    clearInterval(countdownTimer);
    document.getElementById("countdown").innerHTML = "Completed";
  } else {
    seconds--;
  }
}
let countdownTimer = setInterval("timer()", 1000);
<span id="countdown" class="timer"></span>

Now, if I place all the above code within the following function timerScript(), followed by a call to the function, the ReferenceError appears. I'm not even running the if(!foo) { return } but am still getting an error.

What am I missing here?

Here is the CodePen that does not work

function timerScript() {

  code here....

}

timerScript();

function timerScript() {
  let upgradeTime = 535680;
  let seconds = upgradeTime;

  function timer() {
    let days = Math.floor(seconds / 24 / 60 / 60);
    let hoursLeft = Math.floor(seconds - days * 86400);
    let hours = Math.floor(hoursLeft / 3600);
    let minutesLeft = Math.floor(hoursLeft - hours * 3600);
    let minutes = Math.floor(minutesLeft / 60);
    let remainingSeconds = seconds % 60;

    function pad(n) {
      return n < 10 ? "0" + n : n;
    }
    document.getElementById("countdown").innerHTML = `${pad(days)}: ${pad(hours)}: ${pad(minutes)}: ${pad(remainingSeconds)}`;
    if (seconds == 0) {
      clearInterval(countdownTimer);
      document.getElementById("countdown").innerHTML = "Completed";
    } else {
      seconds--;
    }
  }
  let countdownTimer = setInterval("timer()", 1000);
}
timerScript();
<span id="countdown" class="timer"></span>

Viewing all articles
Browse latest Browse all 138163

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>