Search code examples
javascriptdecorator

a decorator function that slows down the execution of another function javascript


a decorator function that slows down the execution of an arbitrary function by 5 seconds.

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*'

attempts were unsuccessful, there are errors in the code

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');

Solution

  • Try this :

    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);