Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Step by Step Number

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

New User

5+ Year Member

joined:Oct 16, 2011
posts: 1
votes: 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
1:57 am on Oct 17, 2011 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 3, 2005
votes: 0

Welcome, something like this.

var nextNumber = 1; // initial value

function my()
if ( nextNumber === 11 ) { nextNumber = 1; }
7:47 am on Oct 17, 2011 (gmt 0)

Senior Member

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

joined:July 3, 2006
posts: 3123
votes: 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.

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members