Achaius
Achaius

Reputation: 6124

How to call the javascript function dynamically

I need to call the javascript function dynamically after some delay, The function display_1, 2, ... n will be dynamically constructed. My script looks like this, but the function never gets triggered if I use the following code, but if I hardcode the function it just seems to be fine.

function display_1() {
alert(1);
}

function display_2() {
alert(2);
}

function display() {
var prefix = 'display_';
for(var i = 1; i < 3; i++) {
setTimeout(prefix.concat(i), 1000);
}

window.onload = display();

Upvotes: 1

Views: 733

Answers (5)

Shadow2531
Shadow2531

Reputation: 12170

If you really want a 1000ms delay between executing the functions, you could do something like this:

window.onload = function() {
    var n = 0;
    var functions = [
        function() {
            alert(1);
            setTimeout(functions[n++], 1000);
        },
        function() {
            alert(2);
            setTimeout(functions[n++], 1000);
        },
        function() {
            alert(3);
        }
    ];
    setTimeout(functions[n++], 1000);
};

(rewrite it in a less-repetitive nature if needed)

Upvotes: 0

xtofl
xtofl

Reputation: 41519

Instead of going via a string, you may as well group the functions into an array:

function display_1() {...}

function display_2() { ... }

var functions = [ display_1, display_2 ];

function display() {
   for( var i = 0; i != functions.length; ++i ) { 
     setTimeout( functions[i], 1000 );
   }
 }

If you want to go further, you may even leave out the explicit function names:

var functions = [
    function() { /*the function_1 implementation*/ 
    },
    function() { /*the function_2 implementation*/
    }
];

Upvotes: 5

Sakthi
Sakthi

Reputation: 363

setInterval('load_testimonial()',5000);//first parameter is your function or what ever the code u want to execute, and second is time in millisecond..

this will help you to execute your function for every given time.

Upvotes: 0

z33m
z33m

Reputation: 6053

It should be

function display_1() {
alert(1);
}

function display_2() {
alert(2);
}

function display() {
var prefix = 'display_';
for(var i = 1; i < 3; i++) {
setTimeout(prefix.concat(i)+'()', 1000);
}
}

window.onload = display;
  1. the string passed to setTimeout should call the function
  2. onload should be set to a function, not its return value

Upvotes: 1

Udo G
Udo G

Reputation: 13141

you have to add the parenthesis so that the function is called:

setTimeout(prefix.concat(i)+"()", 1000);

or simply:

setTimeout(prefix + i + "()", 1000);

Besides of that please note that both functions are called pratically at the same time, because the timers started with ´setTimeout()` start at the same time.

Depending on what you're trying to do you might have a look at setInterval() or start the second timeout at the end of the display_1() function.

Upvotes: 2

Related Questions