Skip to content

模拟C#的 sleep函数

js
let sleep = (delay = 500) => {
	let t = Date.now();
	while (Date.now() - t <= delay) {
		continue;
	}
};
sleep()
let sleep = (delay = 500) => {
	let t = Date.now();
	while (Date.now() - t <= delay) {
		continue;
	}
};
sleep()

实现每隔1秒输出数组中的一个数字 setTimeout()

  • 定时器就是一个异步的任务
  1. let 块级作用域
js
function demo(arr){
	//循环数组
	for(let i=0;i<arr.length;i++){
		//每次打印一个值,五个定时器的延时依次增加1000秒
		setTimeout(()=>{
			console.log(arr[i])
		},1000*i)
	}
}
demo([4,5,6,7,8])
function demo(arr){
	//循环数组
	for(let i=0;i<arr.length;i++){
		//每次打印一个值,五个定时器的延时依次增加1000秒
		setTimeout(()=>{
			console.log(arr[i])
		},1000*i)
	}
}
demo([4,5,6,7,8])
  1. 立即执行函数
js
function demo2(arr){
    for(var i=0;i<arr.length;i++){
        (function(i){
            setTimeout(()=>{
                console.log(arr[i])
            },1000*i)
        })(i)  
    }
}
demo2([4,5,6,7,8])
function demo2(arr){
    for(var i=0;i<arr.length;i++){
        (function(i){
            setTimeout(()=>{
                console.log(arr[i])
            },1000*i)
        })(i)  
    }
}
demo2([4,5,6,7,8])

每隔几秒自动执行函数 setInterval()

js
//每隔一秒自动执行方法(多次执行)
var c=0;
function showLogin()
{
	alert(c++);
}
//setInterval方法或字符串 ,毫秒,参数数组(方法的))
setInterval("showLogin()","1000");//showLogin()函数名一定要带括号
//每隔一秒自动执行方法(多次执行)
var c=0;
function showLogin()
{
	alert(c++);
}
//setInterval方法或字符串 ,毫秒,参数数组(方法的))
setInterval("showLogin()","1000");//showLogin()函数名一定要带括号

等待函数

JavaScript 提供了 setTimeout 函数,但是它并不返回 Promise 对象,所以我们没办法使用 async 作用在这个函数上,但是我们可以封装等待函数。

js
const wait = (ms) => new Promise((resolve)=> setTimeout(resolve, ms))

const asyncFn = async () => {
  await wait(1000)
  console.log('等待异步函数执行结束')
}

asyncFn()
const wait = (ms) => new Promise((resolve)=> setTimeout(resolve, ms))

const asyncFn = async () => {
  await wait(1000)
  console.log('等待异步函数执行结束')
}

asyncFn()