homepage Welcome to WebmasterWorld Guest from 54.204.249.184
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Step by Step Number
luckybutt1987




msg:4375198
 7:47 pm on Oct 16, 2011 (gmt 0)

hello i am new in javascript.

i need a function that works like this.

function my()
{
var ranNum= [b]some function here that give me step by step number on every call i.e on 1st call to my() it make number 1 and on second call it make number 2. i dont need random.[/b]
if (ranNum == 1){
document.write('<p>1</p>');
}
if (ranNum == 2){
document.write('<p>2</p>');
}
}


also one thing more that on the first call must number 1 should generate and on 2nd call must number 2 should generate and after a givin limit its start again from 1 .

Please help me i cant figure it out.
thank you

 

daveVk




msg:4375284
 1:57 am on Oct 17, 2011 (gmt 0)

Welcome, something like this.

var nextNumber = 1; // initial value

function my()
{
document.write('<p>'+nextNumber+'</p>');
nextNumber++;
if ( nextNumber === 11 ) { nextNumber = 1; }
}

penders




msg:4375360
 7:47 am on Oct 17, 2011 (gmt 0)

Or, to avoid the use of a global variable you could create a property of the function object itself to emulate a static variable (a variable that is local to the function but holds its value between function calls) - although it's not strictly local since you can read my.ranNum from outside the function.

function my() { 
// Reset if not already defined or greater than some max limit
if ((typeof my.ranNum == 'undefined') || (my.ranNum > 1000)) {
my.ranNum = 0;
}
my.ranNum++;
document.writeln(my.ranNum);
}
my(); // 1
my(); // 2
my(); // 3
document.writeln(my.ranNum); // 3


Or, you could use this.ranNum inside the function. Although this creates a global variable - a property of the window object.

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved