為什麼setTimeout()在Repl.it的JavaScript環境中回傳[object Object]

Charlie W
Feb 4, 2021

--

Meme: actually Repl.it give you node.js repl when you try to create a JavaScript repl.

答:因為即使在Repl.it選擇建立一個JavaScript的repl,Repl.it給你的依舊是Node.js環境的repl……😂

目錄

setTimeout()在Node.js環境會回傳什麼?
Timeout object(<Timeout>)是什麼?
如何看到MDN文件提到的positive integer value
positive integer value是什麼?

在Repl.it選擇建立一個JavaScript環境的repl
就算在建立新repl的時候選擇JavaScript
即使在建立repl時設定環境為JavaScript,Repl.it最終提供的還是Node.js的環境
Repl還是會給你Node.js的環境

那麼setTimeout()在Node.js環境會回傳什麼?

答:回傳 Timeout object

Ref. 1: setTimeout() returns a Timeout object that can be used to reference the timeout that was set.

Ref. 2: Returns: <Timeout> for use with clearTimeout()

Timeout object(<Timeout>)又是什麼?

答:由setTimeout()setInterval()回傳的物件,可以傳給clearTimeout()clearInterval()來取消其他原本預計要執行的行為。

Ref.: This object is created internally and is returned from setTimeout() and setInterval(). It can be passed to either clearTimeout() or clearInterval() in order to cancel the scheduled actions.

MDN文件說明setTimeout()會回傳positive integer value,如何看到這個結果?

According to MDN specification, setTimeout() will return a timeoutID.

答:在Chrome瀏覽器(按下F12呼叫)的DevTools,貼上程式碼後按下鍵盤Enter執行就可以了。

使用setTimeout(),讓第二行的console.log(“hello world”)延遲3000毫秒才執行。注意:延遲執行≠阻擋接下來程式碼的執行。
Running setTimeout() in Chrome’s DevTool

根據Chrome DevTools的文件setTimeout()在Chrome的行為可參考MDN。

setTimeout() in Chrome DevTools document will redirect to MDN specification.
Chrome DevTools文件的setTimeout()會導向MDN setTimeout()的頁面。

positive integer value又是什麼?

答:是一種ID,此ID可以傳給clearTimeout()來取消timeout行為。

上面的程式碼貼到DevTools後,第二行的console.log("hello world")會被取消。結果如下圖:

JavsScript code demonstration in Chrome’s DevTools
console.log(“hello world”)被window.clearTimeout取消,故不會被執行

Ref.: The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout.

--

--

Charlie W
0 Followers

想要從PM變成面對PM的人😌