簡體   English   中英

使用setTimeout()實現延遲函數並傳遞可選參數(Javascript)

[英]Implementing a delay function using setTimeout() with passing optional arguments (Javascript)

我試圖通過從頭開始實現中間函數來掌握Javascript。 目前正在嘗試實現延遲函數,該函數執行在等待時間(等待)之后作為參數傳遞的任意函數。 這還需要能夠轉發額外傳遞的參數作為被延遲函數的額外參數。

到目前為止我所做的並不是在setTimeout()中調用該函數。 我不確定它是語法錯誤還是我完全錯過了這一點。 我在這里查看了類似的問題,並試圖實現一些建議的結果,但似乎沒有人考慮額外的論點方面。 無論如何,這是我現在擁有的。

    var exampleDelay = function (func, wait) {
      return function () {
        setTimeout(func.apply(this, arguments), wait);
      }
    };

任何幫助解決這個問題都將受到贊賞(或者,如果有人能指出我可能錯過的答案)。

Fran打敗了我,但只是為了變化。 如果你想立刻提供所有參數,這可能是一個選擇

  var exampleDelay = function(callback,wait,args) { var args = [].slice.call(arguments) // get the parent arguments and convert to an array args.splice(0,2); // remove the first two argument which are the fuction supplied and the wait time // a fuction to call the supplied function var callnow = function() { var params = arguments; // get the child arguments var context = this; setTimeout(function(){ callback.apply(context, params) // call the function }, wait); } callnow.apply( this, args ) // use apply to supply the arguments extracted from the parrent }; exampleDelay(console.log, 1000,"hey") exampleDelay(console.log, 5,"hey", "there") 

 callnow.apply( this, args ) // we then call the function with apply and supply args extracted from the parent 

好吧,您可以稍后處理函數驗證,以確保第一個參數是一個函數

您從exampleDelay返回的函數是您稍后調用的函數。 要在調用該函數時保留arguments ,直到計時器執行它,您可以將預期函數包裝在計時器內的匿名函數中。 然后在里面你可以使用apply來傳遞先前存儲的參數。 與下面類似。

 var exampleDelay = function(func, wait) { return function() { var params = arguments; var context = this; setTimeout(function(){ func.apply(context, params) }, wait); } }; var func1 = function(a, b) { console.log(a + b); } var func2 = function(a, b, c) { console.log(a, b, c); } var x = exampleDelay(func1, 1000); var y = exampleDelay(func2, 2000); x(12, 15); y('How', 'Are', 'You?'); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM