循环jquery中的随机数

时间:2015-02-26 09:11:57

标签: jquery loops random numbers

我会为每个循环提供另一个随机数,但它不想要工作... 我不知道为什么。

 $(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);
        }

    }

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分: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