JS中setInterval、setTimeout不能傳遞帶參數的函數的解決方案

來源:互聯網
上載者:User

標籤:style   blog   color   io   使用   ar   div   cti   sp   

在JS中無論是setTimeout還是setInterval,在使用函數名作為調用控制代碼時都不能帶參數,而在許多場合必須要帶參數,接下來為大家介紹具體的解決方案

在JS中無論是setTimeout還是setInterval,在使用函數名作為調用控制代碼時都不能帶參數,而在許多場合必須要帶參數, 
這就需要想方法解決。 
一、採用字串形式:——(缺陷)參數不能被周期性改變 
setInterval("foo(id)",1000); 
二、匿名函數封裝 (推薦) 

window.setInterval(function() { foo (id); }, 1000); 

這樣就可以周期性執行foo(id)這個函數,而且把變數id傳遞進去; 
三、定義返回無參函數的函數 

function foo(id) { alert(id); } function _foo(id) { return function() { foo(id); } } window.setInterval(_foo(id),1000); 

這裡定義了一個函數_foo,用於接收一個參數,並返回一個不帶參數的函數,在這個函數內部使用了外部函數的參數,從而對其調用,不需要使用參數。 
在 window. setInterval函數中,使用_foo(id)來返回一個不帶參數的函數控制代碼,從而實現了參數傳遞的功能。 
四、修改setInterval 

function foo(id) { alert(id); } var _sto = setInterval; window.setInterval = function(callback,timeout,param) { var args = Array.prototype.slice.call(arguments,2); var _cb = function() { callback.apply(null,args); } _sto(_cb,timeout); } window.setInterval(hello,3000,userName); 

以上的所有方法也適合setTimeout。

JS中setInterval、setTimeout不能傳遞帶參數的函數的解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.