【问题标题】:Random Number in a loop jquery循环jquery中的随机数
【发布时间】:2015-04-28 14:04:36
【问题描述】:

我会为每个循环一个其他随机数,但它不希望工作...... 我不知道为什么。

 $(document).ready(function(){

        setTimeout("execute()",5000);

    })

    function execute(){
        for(i=0;i<=5;i++){
            var zWindow = $(window).height();
            var yWindow = $(window).width();
            var z=Math.floor((Math.random() * zWindow) + 1);
            var y=Math.floor((Math.random() * yWindow) + 1);
            $("#egg").css({
                "top": z,
                "left": y
            });
            $("#egg").delay(1000).fadeIn(10).delay(3000).fadeOut(100);
        }

    }

【问题讨论】:

  • execute() 函数中循环*5 的意义何在?

标签: jquery loops random numbers


【解决方案1】:

要停止间隔,请使用clearInterval()- 函数:

$(document).ready(function(){

    var timesRun = 0; 
    var interval = setInterval(execute, 5000); //only use functionname here

    function execute(){

        timesRun += 1;
        var zWindow = $(window).height();
        var yWindow = $(window).width();

        var z = Math.floor((Math.random() * zWindow) + 1);
        var y = Math.floor((Math.random() * yWindow) + 1);

        $("#egg").css({
            "top": z,
            "left": y
        });
        $("#egg").delay(1000).fadeIn(10).delay(3000).fadeOut(100);

        if(timesRun === 5){
            clearInterval(interval);
        }

     }
});

Demo

参考

JS Timing

【讨论】:

    【解决方案2】:

    您需要 setInterval 而不是 setTimeout,它只会执行一次:

    // and use execute directly instead of "execute()"
    setInterval(execute, 5000);
    

    【讨论】:

    • 但现在它一遍又一遍地运行,我只想要 5 次 :)
    猜你喜欢
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-04
    • 2020-12-15
    • 2013-10-28
    相关资源
    最近更新 更多