homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

Step by Step Number

Msg#: 4375196 posted 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){
if (ranNum == 2){

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



WebmasterWorld Senior Member 5+ Year Member

Msg#: 4375196 posted 1:57 am on Oct 17, 2011 (gmt 0)

Welcome, something like this.

var nextNumber = 1; // initial value

function my()
if ( nextNumber === 11 ) { nextNumber = 1; }


WebmasterWorld Senior Member penders us a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month

Msg#: 4375196 posted 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(); // 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