www.webdeveloper.com
Results 1 to 4 of 4

Thread: alert function not working

  1. #1
    Join Date
    Aug 2006
    Posts
    301

    Question alert function not working

    Code:
    <script>
    
    var timer = 0;
    
    function SpellItOut(word)
    {
    
    var temp = word[timer];
    timer += 1;
    
    //why does this line alert the string 'temp' that i pased to it?
    setTimeout("alert('temp')",2000); 
    
    //but this one does not alert the string stored in var temp?
    setTimeout("alert(temp)",2000);
    
    }
    </script>
    
    <p><a href="javascript:SpellItOut('welcome')">welcome</a></p>
    2 questions are in the comments. thanks guys!

  2. #2
    Join Date
    Aug 2006
    Posts
    301

    this is the code

    Code:
    <script>
    
    var timer = 0;
    
    function SpellItOut(word)
    {
    
    var temp = word[timer];
    
    timer += 1;
    
    if( timer >= word.length ){ timer = 0; }
    
    alert(temp);
    setTimeout("alert(temp)",2000);
    
    }
    
    </script>
    
    <p><a href="javascript:SpellItOut('welcome')">welcome</a></p>
    in the code above why does
    Code:
    alert(temp);
    spell out the word each time i click the link, but
    Code:
    setTimeout("alert(temp)",2000);
    not do the same thing 2 seconds later, the setTimeOut doesn't work at all, but it should run the same alert() that is executing on the line right above it?
    Last edited by bsmbahamas; 04-10-2010 at 07:09 PM.

  3. #3
    Join Date
    Aug 2007
    Posts
    3,767
    Because when you pass a string to setTimeout, it executes in global scope. That means that only global variables are accessible. So one bad option would be to make temp a global variable, but a better option would be this.
    Code:
    setTimeout(function(){alert(temp);},2000);
    You should never pass a string to setTimeout, always use a function instead.
    Great wit and madness are near allied, and fine a line their bounds divide.

  4. #4
    Join Date
    Aug 2006
    Posts
    301

    thanks Declan1991

    Quote Originally Posted by Declan1991 View Post
    Because when you pass a string to setTimeout, it executes in global scope. That means that only global variables are accessible. So one bad option would be to make temp a global variable, but a better option would be this.
    Code:
    setTimeout(function(){alert(temp);},2000);
    You should never pass a string to setTimeout, always use a function instead.
    i'll modify and try again, and i guess that means i shuld have titled this post setTimeout() not working properly too, lol

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles