user1460015
user1460015

Reputation: 2003

Reference Error when calling function inside setTimeout

I keep getting a Reference Error inside the setTimeout function.
Below is the code in javascript file

( function( $, undefined ) {

  $( document ).ready( init );

  function init() {
    registerEventListeners();
  }

  function registerEventListeners() {
    $( '.start_countdown').click( handleStart );
    $( '.end_countdown').click( handleEnd );
  }

  var countdown;
  var countdown_number;

  function handleStart() {
    countdown_number = 11;
    countdown_trigger(countdown_number);
  }

  function countdown_trigger() {
    if (countdown_number > 0) {
      countdown_number --;
      document.getElementById('countdown_text').innerHTML = countdown_number;
      if (countdown_number > 0) {
          countdown = setTimeout('countdown_trigger()', 1000);
      }
    }
  }

  function handleEnd() {
    clearTimeout(countdown);
  }

})( jQuery );  

In the jade.js file:

extends layout

append scripts
  script(src='/javascripts/countDownRedirect.js')

block content
  h1= title

  p Redirecting you to your documents shortly

  div
    button.start_countdown#start Start Countdown
    button.end_countdown#end End Countdown

  div#countdown_text Placeholding text

Reference Error: 'countdown_trigger()' not defined

When the page is loaded everything appears to work fine.
Clicking the start button displays 10 but then throws the reference error. Any suggestions?
Thanks

Upvotes: 0

Views: 1629

Answers (2)

jfriend00
jfriend00

Reputation: 707258

To explain what's going on and why it doesn't work - when you pass a string to setTimeout(), the string is evaluated by eval() in the global scope. That means that no local functions or variables are available in that global scope. Since your countdown_trigger() function is declared inside another function, it is not in the global scope and thus won't be available to eval() and thus it doesn't work when you pass it to setTimeout().

This is one of many reasons to never pass strings to setTimeout().

Instead pass a real function reference which is evaluated in your current scope like this:

setTimeout(countdown_trigger, 1000);

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

When you use quotes in setTimeout you're invoking eval which is not a good idea. Try passing a reference to the function instead of a string:

countdown = setTimeout(countdown_trigger, 1000);

Upvotes: 3

Related Questions