JavaScript定时器及回调用法
循环定时任务
// 假设现在有这样一个需求:我需要请求一个接口,根据返回结果判断需不需要重复请求,直到达到某一条件为止,停止请求执行某操作
<script type="text/javascript">
var timer;
var index = 0;
function tim(){
timer = setInterval(function(){
index++;
console.log(Math.random())
if (index === 5) {
window.clearInterval(timer)
}
}, 500);
}
</script>
循环请求并获取返回值 - 拿到返回值后执行操作
回调函数方法
<script>
function getSomething(cb) {
var r = 0;
setTimeout(function() {
r = 2;
cb(r);
}, 100);
}
function compute(x) {
alert(x * 2);
}
getSomething(compute);
</script>
promise方法
function getSomething() {
var r = 0;
return new Promise(function(resolve) {
setTimeout(function() {
r = 2;
resolve(r);
}, 10);
});
}
function compute(x) {
alert(x * 2);
}
getSomething().then(compute);
generator
function getSomething() {
var r = 0;
setTimeout(function() {
r = 2;
it.next(r);
}, 10);
}
function *compute(it) {
var x = yield getSomething();
alert(x * 2);
}
var it = compute();
it.next();
promise + generator
function getSomething() {
var r = 0;
return new Promise(function(resolve) {
setTimeout(function() {
r = 2;
resolve(r);
}, 10);
});
}
function* compute() {
var x = yield getSomething();
alert(x * 2);
}
var it = compute();
it.next().value.then(function(value) {
it.next(value);
});
ES7 - 终极方案
<script type="text/javascript">
function getSomething() {
var r = 0;
return new Promise(function(resolve) {
setTimeout(function() {
r = 2;
resolve(r);
}, 10);
});
}
async function compute() {
var x = await getSomething();
alert(x * 2);
}
// 直接调用compute()方法 -> x为同步请求返回结果,输出4
compute();
// 表示getSomething获取返回值后执行resolve状态 ->
// 当.then()前的方法执行完后再执行then()内部的程序,这样就避免了,数据没获取到等的问题
getSomething().then(compute);
</script>