Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New Coder
    Join Date
    May 2004
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    setTimeout function problem

    I have coded a function Blink(row,col) that uses the setTimeout function to alternately display two images.
    Code:
    function Blink(row,col){
    	var blinkId="ex"+row.toString()+col.toString();
    	var imgName=document.getElementById(blinkId).src;
    	var indx=imgName.indexOf("blank");
    	var imgNum=(indx==-1)? 0:3;
    	document.getElementById(blinkId).src=Img[imgNum];
    	//window.setTimeout("Blink(row,col)",700);
    	Xrow=row;
    	Xcol=col;
    	window.setTimeout("Blink(Xrow,Xcol)",700);
    }
    The routine works, but it only works because one of the original statements has been commented out and I added the last three statements. If I use the original code I get an error telling me that 'row' is not defined. What am I missing in my understanding of JavaScript?
    Thanks for your wisdom.

  • #2
    Regular Coder
    Join Date
    Jul 2005
    Posts
    116
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The problem was that row and col are parameters to your function and they don't exist in the context that Blink is called from 700ms later. When you set Xrow and Xcol to row and col respectively you created new global variables (actually properties of the window object) that could be used in the context that Blink is called from.

    You could also have done it like this:
    Code:
    window.setTimeout("Blink("+row+","+col+")",700);
    That way you don't create unnecessary global variables.

  • #3
    Kor
    Kor is offline
    Red Devil Mod Kor's Avatar
    Join Date
    Apr 2003
    Location
    Bucharest, ROMANIA
    Posts
    8,478
    Thanks
    58
    Thanked 379 Times in 375 Posts
    note that, using global variables you may use as parameters even objects, arrays, aso., while using the local passed parameter I guess that you may pass strings only.
    KOR
    Offshore programming
    -*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

  • #4
    New Coder
    Join Date
    May 2004
    Posts
    25
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Thanks!

    Mongus & Kor,

    Thank you for your assistance. I really wanted to call the setTimeout() function without declaring global variables. I hadn't realized that the parameter in setTimeout was a string that contains JavaScript code. Changing the statement to window.setTimeout("Blink("+row+","+col+")",700); solved the problem.


  •  

    Posting Permissions

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