1

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

2 Answers 2

5
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);
Sign up to request clarification or add additional context in comments.

2 Comments

TIL you can specify setTimeout parameters like that.
setTimeout(): Note that passing additional parameters to the function in the first syntax does not work in Internet Explorer 9 and below. If you want to enable this functionality on that browser, you must use a polyfill
1

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);

Comments

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.