作者:手机用户2502887971_699 | 来源:互联网 | 2023-01-31 17:03
我有一个我在Bookmarklet中使用的jQuery代码.它会逐一点击页面上的所有按钮("Unfollow"类),每个按钮之间有一个随机时间...
Javascript: (function() {
var unfollowButtOns= $('button.Unfollow');
var index = unfollowButtons.length - 1;
unfollow();
function unfollow() {
if (index >= 0) {
$(unfollowButtons[index--])
.click();
setTimeout(unfollow, Math.floor((Math.random() * 1000) + 500));
}
}
})();
我想在完成循环后再次运行上述功能两次.
只是再次运行该函数会导致它与第一个函数调用并行运行.
如何在没有它们的情况下运行unfollow()函数2到3次并行运行?
1> Ezra Chu..:
试试这种方式(使用ES6 Promises):
var runUnfollow = function() {
return new Promise(function(resolve, reject){
var index = unfollowButtons.length - 1;
// fencepost for the loop
var p = Promise.resolve();
// we stop execution at `i == 0`
for (var i = index; i >= 0; i--) {
// run the promise
// then set `p` as the next one
p = p.then(unfollowTimeout.bind(null, i));
}
// make sure we run the last execution at `i == 0`.
p.then(function(){
resolve();
})
function unfollowTimeout(i){
// return a promise to run `unfollow` and a `setTimeout`
return new Promise(function(resolve,reject){
unfollow(i);
setTimeout(resolve, Math.floor((Math.random() * 1000) + 500));
})
}
function unfollow(i) {
$(unfollowButtons[i])
.click();
}
})
}
// run three times synchronously
runUnfollow().then(runUnfollow).then(runUnfollow).then(function(){
//finished
});
// another way to run three times synchronously
p = runUnfollow();
for(i=3; i > 0; i--){
p = p.then(runUnfollow);
}
p.then(function(){
//finished
});
// run in parallel
Promise.all([runUnfollow, runUnfollow, runUnfollow])
.then(function(){
//finished
});
编辑:回来再次阅读你的问题,意识到你试图多次运行一切.我编辑过以反映这一点.