- Objective:
- Breadcrumb:
# 概念阐释
## 语义
`setTimeout()`是一个Node API,作用是延迟一个函数或一个代码片段执行的时间。
## 语法
```js
setTimeout(callbackFunction,delay);
```
# 实例
## 使用setTimeout构造异步[[js 异步 Promise 对象|Promise]]
```js
const returnPromistFunction = ()=> {
return new Promise((resolve,reject)=>{
setTimeout(()=>{resolve('I resolve')},1000);
});
};
const prom = returnPromistFunction();
```
- Promise 里是一个匿名函数
- setTimeout里也是一个匿名函数
## 非异步下的实例
```js
console.log("This is the first line of code in app.js.");
const usingSTO = () => {
console.log("This line of code will log to the console last.");
};
setTimeout(usingSTO,1000 );
console.log("This is the last line of code in app.js.");
```
# 相关内容
#### clearTimeout
# 问题
使用异步函数构造Promise:
1. 函数名为returnPromistFunction
# 问题答案
```js
let returnPromiseFunction = () => {
return new Promise((resolve,reject)=>{
setTimeout(()=>{
let num = 5;
if(num < 5){ resolve('Hello World!')}
else{reject('Uh-oh!')};
},1000)
})
};
//回调,注意函数的回调与变量的回调不同
returnPromiseFunction()
.then((resolvedValue)=>{
console.log(resolvedValue);
})
.catch((rejectionReason)=>{
console.log(rejectionReason);
});
```
待解决的结果

# 参考资料