setTimeout -- 使用方法

基本函数

setTimeout(function(){
    console.log("hello setTimeout")
},2000)
// 2秒钟后打印 hello setTimeout

函数调用 

// 调用方式一  '将函数当做字符串传入'
function fn(num){
    console.log(num +100)
};
setTimeout("fn(111)",1000);  // 注意此处调用用函数的时候需要写成字符串传参,否则会立即执行函数。
// 打印结果 211

// 调用方式二  在函数中返回一个匿名函数,直接在setTimeout中调用
function addfn(num){
  return function(){
    console.log(num+100)
  }
}
setTimeout(addfn(111),2000)
// 打印结果 211

获取传递过来的函数的返回值

// 普通函数获取返回值
function fn(num){
    return num +100
};
let result = fn(111);
console.log(result);

  
// 获取返回函数中的返回值
function f(num){
  return function(){
    return num + 121;
  }
};
let ff = f(100)
console.log(ff()) // 221

 未完,待续,如何在setTimeout中获取函数的返回值

  

原文地址:https://www.cnblogs.com/rose-sharon/p/11670135.html