Reputation: 81
I would like to do this:
var whatever = myfunction;
var time = 200;
setTimeout(whatever, time);
function myfunction() {
//do something
}
It's not working am I am unsure why
Better example: Here is the html Html:
<div id="example1" class="example-card" style="visibility: hidden;"></div>
<div id="example2" class="example-card" style="visibility: hidden;"></div>
Here is the JS JS:
function example1() {
$("#example1").css('visibility', 'visible');
}
function example2() {
$("#example2").css('visibility', 'visible');
}
$(window).on("load", function(){
var time = 0;
$('.example-card').each(function() {
var exampleId = this.id;
setTimeout(exampleId, time);
time = time + 200;
});
});
Thanks,
Upvotes: 0
Views: 153
Reputation: 2377
function example1() {
$("#example1").css('visibility', 'visible');
console.log("example1");
}
function example2() {
$("#example2").css('visibility', 'visible');
console.log("example2");
}
$(window).on("load", function() {
var time = 0;
var func = 0;
$('.example-card').each(function() {
switch(this.id) {
case "example1":
func = example1;
break;
case "example2":
func = example2;
break;
default:
func = 0;
break;
}
if (func) {
setTimeout(func, time);
time = time + 2000;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="example1" class="example-card" style="visibility: hidden;"></div>
<div id="example2" class="example-card" style="visibility: hidden;"></div>
Upvotes: 1
Reputation: 184
Currently you're calling the string in your code, which is not possible:
function test() {
console.log('Test');
}
var id = 'test';
id(); // Fails, this is the string.
You can get the function through window
, since it's global:
window[id](); // Success, this is a function.
This works, but is unsafe: you can also call other functions declared in the window. For example if your ID is alert
, it'll call the alert function.
The best way of doing this is by declaring the functions in an object:
var callbacks = {
test: function() {
console.log('Test')
}
};
var id = 'test';
callbacks[id](); // Calls the function in the object
Upvotes: 2
Reputation: 3827
var whatever = myfunction;
var time = 2000;
setTimeout(whatever, time);
function myfunction() {
alert("hi");
}
Upvotes: 2