[問題] 關於setTimeout寫法

看板Ajax作者 (blues520520)時間5年前 (2018/09/15 21:20), 編輯推噓3(3023)
留言26則, 7人參與, 5年前最新討論串1/2 (看更多)
//錯誤寫法 setTimeout(console.log(2),1000); //正常寫法.... setTimeout(function(){ console.log(2); },1000) //簡短寫法 setTimeout('console.log(2)',1000); 為什麼錯誤寫法也會印出2,不懂? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 1.161.172.182 ※ 文章網址: https://www.ptt.cc/bbs/Ajax/M.1537017644.A.50E.html

09/15 21:37, 5年前 , 1F
setTimeout第一個參數是函數,時間到會執行函數的內容
09/15 21:37, 1F

09/15 21:38, 5年前 , 2F
至於直接把 console.log(2)這種敘述當函數放進去...
09/15 21:38, 2F

09/15 21:38, 5年前 , 3F
我就不知道了。 求解+1
09/15 21:38, 3F

09/15 21:47, 5年前 , 4F
你的錯誤寫法相當於 http://tinyurl.com/y964rlkk
09/15 21:47, 4F

09/15 22:25, 5年前 , 5F
setTimeout(console.log(2),1000);
09/15 22:25, 5F

09/15 22:26, 5年前 , 6F
console.log(7);
09/15 22:26, 6F

09/15 22:31, 5年前 , 7F
//output: 2 7 故it is not a callback
09/15 22:31, 7F

09/15 22:32, 5年前 , 8F
setTimeout(function(){console.log(2)},1000);
09/15 22:32, 8F

09/15 22:33, 5年前 , 9F
setTimeout(function(){console.log(2)},1000);
09/15 22:33, 9F

09/15 22:37, 5年前 , 10F
console.log(7); //output 7 2 2 there are two cbs
09/15 22:37, 10F

09/15 23:30, 5年前 , 11F
test = function(){
09/15 23:30, 11F

09/15 23:31, 5年前 , 12F
print 2;
09/15 23:31, 12F

09/15 23:31, 5年前 , 13F
我知道他沒有等一秒後才執行,而是立即顯示,不懂錯
09/15 23:31, 13F

09/15 23:31, 5年前 , 14F
誤寫法還能正常執行出來,不會報錯
09/15 23:31, 14F

09/15 23:31, 5年前 , 15F
return void();
09/15 23:31, 15F

09/15 23:31, 5年前 , 16F
}
09/15 23:31, 16F

09/15 23:32, 5年前 , 17F
setTimeout(test,1000);
09/15 23:32, 17F

09/15 23:33, 5年前 , 18F
那錯誤寫法就像這種效果,不知道這樣你是否比較好懂@@
09/15 23:33, 18F

09/15 23:36, 5年前 , 19F
上面錯了,應該是 setTimeout(test(),1000);
09/15 23:36, 19F

09/15 23:36, 5年前 , 20F
丟入 setTimeout 的是 function 跑完後返回的結果而不
09/15 23:36, 20F

09/15 23:36, 5年前 , 21F
是 function 本身
09/15 23:36, 21F

09/15 23:45, 5年前 , 22F
原po 你懂run to completion嗎?希望你再仔細看看上文!
09/15 23:45, 22F

09/16 13:56, 5年前 , 23F
謝謝各位解釋
09/16 13:56, 23F

09/16 22:29, 5年前 , 24F
這問題就好像別人預期要你放把麵包放到烤麵包機裡面送過去
09/16 22:29, 24F

09/16 22:29, 5年前 , 25F
但是你卻把烤好的麵包送了過去XD
09/16 22:29, 25F

09/17 14:56, 5年前 , 26F
mdn 有寫啊...
09/17 14:56, 26F
文章代碼(AID): #1RdGSiKE (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1RdGSiKE (Ajax)