简体   繁体   English

由于某些原因,返回setTimeout返回1

[英]returning setTimeout returns 1 for some reason

I'm trying to return setTimeout() that prints out "Hello" after .5 sec. 我试图返回setTimeout(),它在0.5秒后打印出“ Hello”。 It is returning an unwanted 1 before "Hello". 它在“ Hello”之前返回一个不需要的1。 Can anyone figure this out? 谁能解决这个问题?

 let c = () => setTimeout(() => console.log("hello"), 500) console.log(c()); //1 //hello 

You're getting 1 because setTimeout returns its unique identifier which JS uses to identify the timeout. 您将得到1,因为setTimeout返回其唯一标识符,JS使用该标识符来标识超时。

This means when you console.log(c()) you're going to get the return of setTimeout which is its id. 这意味着当您console.log(c())您将获得setTimeout的返回值,即它的ID。

To fix this, you can just call c() without logging its return value: 为了解决这个问题,您可以调用c()而不记录其返回值:

 const c = () => setTimeout(() => console.log("hello"), 500) c(); // hello 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM