【问题标题】:Lots of setTimeout() - how to srink?很多 setTimeout() - 怎么喝?
【发布时间】:2017-12-23 17:03:59
【问题描述】:

我想使用 javascript 制作一个 3d 立方体的动画。我已经制作了它需要的方法。就像转动它一样。但是为了使它们动画化,我以 2000 的间隔添加了 setTimeout() 函数。

Opps!这里有很多 setTimeout 函数!

有什么方法可以让我创建一个方法来简单地运行下一个代码......??? 喜欢这个!!!

$(".cube .box").turn("right").wait(2000).turn("back").wait(300).turn("left")

简单但有效!!! :-)

setTimeout(function() {
        $(".cube .box").turn("right");
        setTimeout(function() {
            $(".cube .box").turn("back");
            setTimeout(function() {
                $(".cube .box").turn("left");
                setTimeout(function() {
                    $(".cube .box").turn("top");
                    setTimeout(function() {
                        $(".cube .box").turn("bottom");
                        setTimeout(function() {
                            $(".cube .box").turn("front");
                        }, 2000);
                    }, 2000);
                }, 2000);
            }, 2000);
        }, 2000);
    }, 2000);

【问题讨论】:

  • 只需使用delay 而不是wait 就完成了...
  • turn 到底是什么?它不是一个 jQuery 函数。

标签: javascript


【解决方案1】:
 const directions = ["right", "back", "left", "top", "bottom", "front"]

 function turn(i = 0){
   if(i >= directions.length) return;
   $(".cube .box").turn(directions[i]);
   setTimeout(turn, 2000, i + 1);
 }

 //Start
 setTimeout(turn, 2000);

只需使用间接递归函数来遍历所有轮次。


或者使用 jquery delay

$(".cube .box")
  .delay(2000)
  .turn("right")
  .delay(2000)
  .turn("back")
  .delay(2000)
  .turn("left")
  .delay(2000)
  .turn("top")
  .delay(2000)
  .turn("bottom")
  .delay(2000)
  .turn("front")

可以简化为:

 ["right", "back", "left", "top", "bottom", "front"].reduce(
   (chain, turn) => chain.delay(2000).turn(turn),
   $(".cube .box")
 );

【讨论】:

    猜你喜欢
    • 2010-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-07-10
    • 2021-03-16
    • 2012-01-23
    • 2015-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多