【问题标题】:a decorator function that slows down the execution of another function javascript一个装饰器函数,它减慢了另一个函数 javascript 的执行速度
【发布时间】:2023-02-14 22:25:15
【问题描述】:

将任意函数的执行速度减慢 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');

【问题讨论】:

    标签: javascript decorator


    【解决方案1】:

    我不太确定理解您要做什么,但您的功能似乎有效。唯一的问题是 setTimeout() 以毫秒而不是秒为单位接受参数,因此如果需要秒,则需要将其乘以 1000:

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

    【讨论】:

      【解决方案2】:

      尝试这个 :

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-29
        • 2015-12-25
        相关资源
        最近更新 更多