"undefined" with setTimeout

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • gomzi
    Contributor
    • Mar 2007
    • 304

    "undefined" with setTimeout

    hi,
    I am posting below my javascript code,
    function displaynames(na me)
    {
    var names = name.split(",") ;
    var t = setTimeout("sho wnames('" + names + "')",5000);
    }

    function shownames(names )
    {
    var i=0;
    while(i<names.l ength)
    {
    alert(names[i]);
    i=i+1;
    }

    Initially displaynames gets called, then after the split, it calls the shownames function. But when i try to display the values through the while loop i get "undefined" instead of the real values.

    Am able to display the values in the displaynames function.

    any idea as to whats going wrong here?
  • mrhoo
    Contributor
    • Jun 2006
    • 428

    #2
    SetTimeout evaluates its first argument to a string,
    so the array is joined before it is passed to shownames.

    Pass the string to displaynames and do the split in shownames:

    Code:
    function displaynames(name){
    	var t = setTimeout("shownames('" + name + "')",5000);
    }
    
    function shownames(name){
    	var names = name.split(",");
    	var i=0, L=names.length;
    	while(i<L){
    		alert(names[i++]);		
    	}
    }

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Changed thread title.

      Comment

      Working...