将变量传递给setTimeout()

时间:2018-04-11 10:24:42

标签: javascript

我想这样做:

var whatever = myfunction;
var time = 200;
setTimeout(whatever, time);

function myfunction() {
    //do something
}

它不起作用我不确定为什么

更好的例子: 这是html HTML:

<div id="example1" class="example-card" style="visibility: hidden;"></div>
<div id="example2" class="example-card" style="visibility: hidden;"></div>

这是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;
    });
});

谢谢,

3 个答案:

答案 0 :(得分:2)

var whatever = myfunction;
var time = 2000;
setTimeout(whatever, time);

function myfunction() {
    alert("hi");
}

答案 1 :(得分:2)

目前您在代码中调用字符串,这是不可能的:

function test() {
    console.log('Test');
}

var id = 'test';

id(); // Fails, this is the string.

您可以通过window获取该功能,因为它是全局的:

window[id](); // Success, this is a function.

这有效,但不安全:您还可以调用窗口中声明的其他函数。例如,如果您的ID为alert,则会调用提醒功能。

执行此操作的最佳方法是声明对象中的函数:

var callbacks = {
    test: function() {
        console.log('Test')
    }
};

var id = 'test';

callbacks[id](); // Calls the function in the object

答案 2 :(得分:1)

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>

相关问题