Kev_T
Kev_T

Reputation: 705

Call javascript function every second

I'm trying to learn javascript, buy now when I try to repeat a function, it won't seem to work.

This is my function:

    function heyhey(el){
    el.style.position = "absolute";
    el.style.top = Math.floor(Math.random()*document.body.clientHeight);
    el.style.left = Math.floor(Math.random()*document.body.clientWidth);
  }
  heyhey(document.getElementById('random'));
  //random is the id of my html div

This works, but I want the function to be called every second

What I've tried to repeat the function:

    function heyhey(el){
            el.style.position = "absolute";
            el.style.top = Math.floor(Math.random()*document.body.clientHeight);
            el.style.left = Math.floor(Math.random()*document.body.clientWidth);
            heyhey();
}
          heyhey(document.getElementById('random'));

I also tried this:

function heyhey(el){
                el.style.position = "absolute";
                el.style.top = Math.floor(Math.random()*document.body.clientHeight);
                el.style.left = Math.floor(Math.random()*document.body.clientWidth);
                setTimeout(heyhey, 5000);
    }
              heyhey(document.getElementById('random'));
              heyhey();

Upvotes: 1

Views: 167

Answers (2)

rvandoni
rvandoni

Reputation: 3397

if you want to avoid the recursion, you can use setInterval function.

a simple example:

var intervalID = window.setInterval(myCallback, 500);

function myCallback() {
  // Your code here
}

if you want to stop the execution of your function you have to call the clearInterval():

clearInterval(intervalID);

Upvotes: 1

Quentin
Quentin

Reputation: 943142

function heyhey(el)

The function expects one argument

setTimeout(heyhey, 5000);

You aren't passing it any. Specify the arguments as the third and onwards arguments to setTimeout.

setTimeout(heyhey, 5000, el);

Upvotes: 5

Related Questions