iT邦幫忙

2

[javascript] setInterval() 設置變數

Zaku 2017-08-28 09:42:337708 瀏覽
  • 分享至 

  • xImage

想問一下關於setInterval在傳遞變數時如何設置比較恰當

var flag=true;

if(flag==true){
var index=0;
setInterval(theFinction,2000,index++);
}

theFinction(index){
console.log(index);
}

假定我要傳送index,讓它顯示0,1,2,3....
但在我不寫成全域變數的情況下,他只會一直跑0,0,0,0,.....

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

2 個回答

1
石頭
iT邦高手 1 級 ‧ 2017-08-28 10:54:14

給你參考一下

https://jsfiddle.net/mnt990x9/

fillano iT邦超人 1 級 ‧ 2017-08-28 11:25:48 檢舉

或是用return function製造出closure:
https://jsfiddle.net/6t29esv7/

Zaku iT邦新手 3 級 ‧ 2017-08-29 09:44:04 檢舉

fillano大return function那是怎麼一直抓到i?全部變數?

fillano iT邦超人 1 級 ‧ 2017-08-31 10:20:20 檢舉

就說是closure阿XD,你去找一下closure的資料,例如:
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Closures

0
froce
iT邦大師 1 級 ‧ 2017-08-28 11:18:01
var flag=true;

function display_index(){
    console.log(index);
    index += 1;
}

index = 0;
// console.log(index);
if(flag == true){
    setInterval(display_index,2000);
}

使用全域變數。

Zaku iT邦新手 3 級 ‧ 2017-08-29 09:39:24 檢舉

大大這樣還是全域變數

我要發表回答

立即登入回答