0

I would for every loop an other random number, but it does not want worke... I don't know why.

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

    }
1
  • Whats the point of the loop*5 in your execute() function? Commented Feb 26, 2015 at 9:12

2 Answers 2

1

For stopping an interval, use the clearInterval()- function:

$(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

Reference

JS Timing

Sign up to request clarification or add additional context in comments.

Comments

1

You need setInterval but not setTimeout which will only execute once:

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

1 Comment

but now it runs over and over, i want just 5 Times :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.