gpt4 book ai didi

javascript - 在另一个函数内部调用带参数的函数

转载 作者:行者123 更新时间:2023-11-28 13:10:07 26 4
gpt4 key购买 nike

我正在尝试构建一种调度程序函数,能够在随机时刻及时调用带有参数的另一个函数。这是我使用 Javascript 的尝试:

function scheduleFunction(t, deltaT, functionName) {

var timeout;
var timeoutID;

function scheduler() {
functionName()

clearTimeout(timeoutID);
timeout = Math.trunc(Math.random() * 2 * deltaT - deltaT) + t;
timeoutID = setTimeout(scheduler, timeout);
}

scheduler();

}

如果我让它调用另一个不需要参数的函数,这个函数就能正常工作。例如:

function printSomething() {
console.log("Printing something...");
}

scheduleFunction(1000, 500, printSomething);

不幸的是,该函数不允许使用参数调用另一个函数,即 - 例如:

function print(string) {
console.log(string);
}

scheduleFunction(1000, 500, print("Hello World!"));

如果可能的话,我应该如何编辑调度程序函数以获得这种结果?

最佳答案

您可以绑定(bind)参数:

scheduleFunction(1000, 500, print.bind(null, "Hello World!"));

function scheduleFunction(t, deltaT, functionName) {
var timeout;
var timeoutID;

function scheduler() {
functionName()

clearTimeout(timeoutID);
timeout = Math.trunc(Math.random() * 2 * deltaT - deltaT) + t;
timeoutID = setTimeout(scheduler, timeout);
}

scheduler();
}

function print(string) {
console.log(string);
}

scheduleFunction(1000, 500, print.bind(null, "Hello World!"));

关于javascript - 在另一个函数内部调用带参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43243815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com