顯示廣告
隱藏 ✕
※ 本文為 terievv 轉寄自 ptt.cc 更新時間: 2018-12-14 13:04:01
看板 Ajax
作者 blues520520 (blues520520)
標題 [問題] 關於setTimeout寫法
時間 Sat Sep 15 21:20:42 2018


//錯誤寫法
setTimeout(console.log(2),1000);

//正常寫法....
setTimeout(function(){
   console.log(2);
},1000)

//簡短寫法
setTimeout('console.log(2)',1000);


為什麼錯誤寫法也會印出2,不懂?

--
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.161.172.182
※ 文章代碼(AID): #1RdGSiKE (Ajax)
※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1537017644.A.50E.html
peanut97: setTimeout第一個參數是函數,時間到會執行函數的內容1F 09/15 21:37
peanut97: 至於直接把 console.log(2)這種敘述當函數放進去...
peanut97: 我就不知道了。 求解+1
eight0: 你的錯誤寫法相當於 http://tinyurl.com/y964rlkk4F 09/15 21:47
JS Bin - Collaborative JavaScript Debugging
[圖]
A live pastebin for HTML, CSS & JavaScript and a range of processors, including SCSS, CoffeeScript, Jade and more... ...

 
lachtchlee: setTimeout(console.log(2),1000);5F 09/15 22:25
lachtchlee: console.log(7);
lachtchlee: //output: 2    7  故it is not a callback
lachtchlee: setTimeout(function(){console.log(2)},1000);
lachtchlee: setTimeout(function(){console.log(2)},1000);
lachtchlee: console.log(7);  //output 7 2 2 there are two cbs
xdraculax: test = function(){11F 09/15 23:30
xdraculax: print 2;
blues520520: 我知道他沒有等一秒後才執行,而是立即顯示,不懂錯13F 09/15 23:31
blues520520: 誤寫法還能正常執行出來,不會報錯
xdraculax: return void();15F 09/15 23:31
xdraculax: }
xdraculax: setTimeout(test,1000);
xdraculax: 那錯誤寫法就像這種效果,不知道這樣你是否比較好懂@@
xdraculax: 上面錯了,應該是 setTimeout(test(),1000);
xdraculax: 丟入 setTimeout 的是 function 跑完後返回的結果而不
xdraculax: 是 function 本身
lachtchlee: 原po 你懂run to completion嗎?希望你再仔細看看上文!22F 09/15 23:45
blues520520: 謝謝各位解釋23F 09/16 13:56
y3k: 這問題就好像別人預期要你放把麵包放到烤麵包機裡面送過去24F 09/16 22:29
y3k: 但是你卻把烤好的麵包送了過去XD
VdustR: mdn 有寫啊...26F 09/17 14:56

--
※ 看板: terievv 文章推薦值: 0 目前人氣: 0 累積人氣: 78 
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇