一个装饰器函数,它减慢了另一个函数javascript的执行

wko9yo5t  于 2023-02-15  发布在  Java
关注(0)|答案(2)|浏览(112)

一个装饰器函数,它使任意函数的执行速度降低5秒。

function someFunction(a, b) {
        console.log(a + b);
    }
function slower(func, seconds) {
// decorator code
}
let slowedSomeFunction = slower(someFunction, 5);
slowedSomeFunction()
// will output to the console "You will get you result in 5 seconds"
//...in 5 seconds will display the result of 'someFunction*'

尝试失败,代码中有错误

function someFunction(x) {
    alert(x);
}

function slower(func, seconds) {
    return function() {
        setTimeout(() => func.apply(this, arguments), seconds);
    }
}

let slowedSomeFunction = slower(alert, 5); 

slowedSomeFunction('You will get you result in 5 seconds');
h4cxqtbf

h4cxqtbf1#

试试这个:

function someFunction(a, b) {
    console.log(a + b);
}

function slower(func, seconds) {
    return function() {
        console.log("You will get your result in " + seconds + " seconds");
        setTimeout(() => func.apply(this, arguments), seconds * 1000);
    }
}

let slowedSomeFunction = slower(someFunction, 5);
slowedSomeFunction(2, 3);
zujrkrfu

zujrkrfu2#

我不太清楚你想做什么,但是你的函数看起来很有效,唯一的问题是setTimeout()参数的单位是毫秒而不是秒,所以如果你想要秒,你需要把它乘以1 000:

function someFunction(x) {
    alert(x);
}

function slower(func, seconds) {
    return function() {
        setTimeout(() => func.apply(this, arguments), seconds*1000);
    }
}

let slowedSomeFunction = slower(someFunction, 5); 

slowedSomeFunction('Chill out, you will get you result in 5 seconds');

相关问题