连续多次运行jQuery函数(对于Bookmarklet)

iag*_*tme 9 javascript jquery

我有一个我在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));
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)

我想在完成循环后再次运行上述功能两次.

只是再次运行该函数会导致它与第一个函数调用并行运行.

如何在没有它们的情况下运行unfollow()函数2到3次并行运行?

Ezr*_*Chu 6

试试这种方式(使用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
  });
Run Code Online (Sandbox Code Playgroud)

编辑:回来再次阅读你的问题,意识到你试图多次运行一切.我编辑过以反映这一点.


Leo*_*ang 4

index单击每个按钮后只需重置并重新启动:

javascript: (function() {
    var unfollowButtons = $('button.Unfollow');
    var index = unfollowButtons.length - 1;
    var totalRuns = 3;
    unfollow();

    function unfollow() {
        if (index < 0 && totalRuns) {
            totalRuns--;
            unfollowButtons = $('button.Unfollow');
            index = unfollowButtons.length - 1;
        }

        if (index >= 0) {
            $(unfollowButtons[index--])
                .click();
            setTimeout(unfollow, Math.floor((Math.random() * 1000) + 500));
        }
    }
})();
Run Code Online (Sandbox Code Playgroud)