实现一个sleep函数
Sunny-117 opened this issue · comments
function sleep(delay: number): Promise<void> {
return new Promise(resolve => {
setTimeout(resolve, delay);
});
}
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const sleep = (time = 0) => new Promise((resolve) => setTimeout(resolve, time))
const sleep = (delay: number) => {
return new Promise(resolve => {
setTimeout(() => {
resolve()
}, delay* 1000)
})
}
额这不对吧, sleep函数的定义固然有延时, 更重要的是还要中断程序并抛出中断异常才对, 比如java:
try{
Thread.sleep(3000);
} catch (InterruptedException e){
e.printStackTrace();
}
我的想法是用while(true)做中断, 或者node环境的话可以用Atomics.wait貌似也可以(因为浏览器环境不支持SharedBuffer了),
不然这个sleep就只是个定时器了.
function sleep (delay = 1000) {
return cb => {
let startTime = +(new Date());
let curTime = startTime;
while (true) {
curTime = +(new Date());
if (curTime - startTime >= delay) {
cb()
break
};
}
throw Error("SLEEP ERROR")
}
}
额这不是对吧,睡眠次数的确定固然有延迟,更重要的是还要中断程序并抛出中断异常才对,比如java:
try{ Thread.sleep(3000); } catch (InterruptedException e){ e.printStackTrace(); }我的想法是用while(true)做中断,或者节点环境的对话可以用Atomics。wait貌似也可以(因为浏览器环境不支持SharedBuffer了), 不过这个sleep只是一个定时器。
function sleep (delay = 1000) { return cb => { let startTime = +(new Date()); let curTime = startTime; while (true) { curTime = +(new Date()); if (curTime - startTime >= delay) { cb() break }; } throw Error("SLEEP ERROR") } }
他们的意思是 因为 返回的是一个promise 所以 可以使用await 来等待时间结束 才继续执行后续代码
function sleep(time) {
return new Promise((res) => {
setTimeout(() => {
console.log(我等待了${time}秒才出现你面前
);
res();
}, time * 1000);
});
}
async function runCode(time) {
console.log(" 我在sleep 之前");
// 等待多少秒
await sleep(time);
console.log(" 我在sleep 之后");
}
runCode(6);
<script>
// 普通版本
function sleep (slTime) {
let start = new Date()
while(new Date - start <= slTime) {}
}
const t5 = new Date()
sleep(3000)
const t6 = new Date()
console.log(t6 - t5)
// promise 实现
function sleep (slTime) {
return new Promise(resolve =>{
setTimeout(resolve,slTime)
})
}
const t1 = new Date();
sleep(3000).then(()=>{
const t2 = new Date();
console.log(t2-t1);
})
// async,await实现
function sleep (slTime) {
return new Promise(resolve =>{
setTimeout(resolve,slTime)
})
}
(async function test(){
const t1 = new Date();
await sleep(3000)
const t2 = new Date();
console.log(t2 - t1);
}())
</script>
function sleep (t = 1000) {
console.log('>>> sleep start');
let startTime = +(new Date());
let curTime = startTime;
while (true) {
curTime = +(new Date());
if (curTime - startTime >= t) break;
}
console.log('>>> sleep finish');
}
function sleep(timeout) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), timeout);
})
}
// test
async function test() {
console.log('start');
await sleep(5000);
console.log('end');
}
test()
function sleep(delay) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, delay);
});
}