等待函数
function wait(ms: number) {
return new Promise<void>(function (reslove) {
setTimeout(() => {
reslove();
}, ms);
});
}
(async function test() {
await wait(1000);
console.warn('等待了 1s');
})();
数据请求未超时,正常返回,超时抛出错误
function wait() {
return new Promise(function (reslove) {
setTimeout(() => {
reslove("数据");
}, 8000);
});
}
function getData() {
return new Promise(function (reslove, reject) {
setTimeout(() => {
reject(new Error("timeout"));
}, 6000);
wait().then((res) => {
if (res) {
console.log("正常接收");
reslove(res);
}
});
});
}
console.log("getData", getData());
数据请求发生错误后间隔调用
正确实现
function simplePoller(queryfn, callback) {
let time = 1000;
const poll = () => {
console.log("time", time);
if (queryfn()) {
callback();
return;
}
setTimeout(poll, time);
time *= 1.5
};
setTimeout(poll, time);
}
console.log("deepQuery", simplePoller(isOK, getData));
非正确实现
function queryFn(num) {
return new Promise(function (reslove, reject) {
setTimeout(function () {
reslove(false);
}, num);
});
}
function callback() {
console.log("执行回调");
}
function simplePoller(queryFn, callback) {
let num = 0;
let aa = 1;
function content() {
num = num + 1;
if (num > 1) {
aa = aa * 1.5;
}
const step = num === 1 ? aa * 1000 : aa * 1000;
console.log("dealty", step);
queryFn(step).then((res) => {
console.log("结果", res);
if (!res) {
content(queryFn, callback);
}
if (res) {
callback();
}
});
}
content();
}
simplePoller(queryFn, callback);
闭包问题
const test = () => {
let num = 0;
function effect () {
num += 1
const message = `现在的值${num}`
return function unmount() {
console.log('message', message);
}
};
return effect;
};
const add = test();
const unmount = add();
console.log('add2', add()());
console.log('add3', add()());
console.log('add4', add()());
console.log('unmount add 5', unmount());
debounce
function debounce(fn, delaty) {
let timer = null;
return function () {
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(function () {
fn();
}, delaty);
};
}
throrrle
function throrrle(fn, delaty) {
let valid = true;
return function () {
if (!valid) {
return;
}
valid = false;
setTimeout(function () {
fn();
valid = true;
}, delaty);
};
}
选择排序
let arr = [1, 3, 8, 9, 7, 6];
function xunaze(arr) {
for (var i = 0; i < arr.length; i++) {
let minIndex = i;
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
if (i !== minIndex) {
let temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
return arr;
}