最近常常遇到這樣的問題:須要間隔多少秒獲取一次數據。實際中,每每採用setInterval來實現,可是當參數傳遞不當時,會出現先延遲了一段時間後再執行獲取的數據的函數。函數
如:code
var data1=0; function count1(){ console.log("count1:",data1++); } setInterval(count1,1000);
此時能夠觀察控制檯,發現打印第一次會有延遲。如: 文檔
查看setInterval官方文檔不難發現:string
var intervalID = window.setInterval(func, delay[, param1, param2, ...]); var intervalID = window.setInterval(code, delay); Parameters
func,A function to be executed every delay milliseconds.
code,
An optional syntax allows you to include a string instead of a function, which is compiled and executed every delay milliseconds. This syntax is not recommended for the same reasons that make using eval() a security risk.it
所以,若是需求確實要先執行如下原函數,再返回該函數給setInterval週期執行。此時能夠以下實現:io
var data2=0; var count2= function(){ console.log("count2:",data2++); return count2;//若不返回時,此函數只會執行一次 } setInterval(count2(),1000);
固然這裏也能夠先執行原函數,再加定時器setInterval,只是這樣寫的不漂亮嗎?爲何不呢console