Vai*_*y07 3 javascript return setinterval
我想在setInterval中返回一个值.我只是想用时间间隔执行一些事情,这就是我尝试过的事情:
function git(limit) {
var i = 0;
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
return 'done';
}
i++;
}, 800);
}
var x = git(5);
console.log(x);
Run Code Online (Sandbox Code Playgroud)
它不起作用.还有其他方法吗?
我将要做的是在特定的时间间隔内制作动画.然后当我达到极限(例如5x blink by $().fadeOut().fadeIn())时,我想返回一个值.
function func_a(limit) {
var i = 0;
var defer = $.Deferred();
var x = setInterval(function () {
$('#output').append('A Running Function ' + i + '<br />');
if (i == limit) {
$('#output').append('A Done Function A:' + i + '<br /><br />');
clearInterval(x);
defer.resolve('B');
}
i++;
}, 500);
return defer;
}
function func_b(limit) {
var c = 0;
var defer = $.Deferred();
var y = setInterval(function () {
$('#output').append('B Running Function ' + c + '<br />');
if (c == limit) {
$('#output').append('B Done Function B:' + c + '<br /><br />');
clearInterval(y);
defer.resolve('A');
}
c++;
}, 500);
return defer;
}
func_a(3).then( func_b(5) ).then( func_a(2) );
Run Code Online (Sandbox Code Playgroud)
这不是很好,它应该打印A,A,A,Done A,B,B,B,B,B,Done B,A,A,Done A但在这里它是混乱的,似乎是延迟runs all function not one after the other但同时.这就是我问这个问题的原因,因为我想回到return defer;我的内心if...
if (i == limit) {
$('#output').append('A Done Function A:' + i + '<br /><br />');
clearInterval(x);
defer.resolve('B');
// planning to put return here instead below but this is not working
return defer;
}
Run Code Online (Sandbox Code Playgroud)
Raz*_*zem 11
你期望它等到间隔结束吗?这对运行时来说真的很痛苦,你会阻止整个页面.JS中的很多东西现在是异步的,所以你必须使用回调,承诺或类似的东西:
function git(limit, callback) {
var i = 0;
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
callback('done');
}
i++;
}, 800);
}
git(5, function (x) {
console.log(x);
});
Run Code Online (Sandbox Code Playgroud)
使用承诺它看起来像这样:
function git(limit, callback) {
var i = 0, promise = new Promise();
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
promise.resolve('done');
}
i++;
}, 800);
return promise;
}
git(5)
.then(function (x) {
console.log(x);
var promise = new Promise();
setTimeout(function () { promise.resolve("hello"); }, 1000);
return promise;
})
.then(function (y) {
console.log(y); // "hello" after 1000 milliseconds
});
Run Code Online (Sandbox Code Playgroud)
编辑:为承诺创建添加了伪示例
Edit2:使用两个承诺
尝试实现callback您的git功能。
function git(limit,callback) {
var i = 0;
var git = setInterval(function () {
console.log(i);
if (i === limit - 1) {
clearInterval(git);
callback('done') // now call the callback function with 'done'
}
i++;
}, 800);
}
var x = git(5,console.log); // you passed the function you want to execute in second paramenter
Run Code Online (Sandbox Code Playgroud)