-1
function main() {
  var abc = document.getElementById('space');

  abc.style.left += 10 + 'px';

  main2();
}

function main2() {
  setInterval(main(), 1000);
}

according to this code value position of space must change in 1 second. but it is not working position is changing only once

t.niese
  • 39,256
  • 9
  • 74
  • 101
  • element is positioned absolute in css? next thing setInterval(main,1000) ; - use declaration not function result. – Maciej Sikora Aug 11 '16 at 10:44
  • 1
    You call `main` immediately and pass the result of the `main` function to the `setInterval` . Check the duplicate for more details. – t.niese Aug 11 '16 at 10:46
  • maciej sikora yes positioning is absolute – Karan Pratap Singh Aug 11 '16 at 10:47
  • An additional note: On the on hand your code creates a `Uncaught RangeError: Maximum call stack size exceeded` error, that you should have mentioned with your question. And either use `setInterval` or and remove the `main2()`, because this will create an additional interval with each iteration, or stay with the `main2()` and use `setTimeout` instead of `setInterval`. – t.niese Aug 11 '16 at 10:54

1 Answers1

0

The main problem here is that you are executing the main function, instead of just passing it. Basically it's like this:

setInterval(function() { /* something inside */ }, 1000);

I can take this function and declare it outside:

function main() {
    // something inside
}
setInterval(main, 1000); // here I just pass the `main` function

What you are doing is not passing, but executing the function:

function main() {
    // something inside
}
setInterval(main(), 1000);
  • is there any diffrence in between setInterval(main,1000) and setInterval(main(),1000) – Karan Pratap Singh Aug 11 '16 at 13:21
  • `setInterval(main(),1000)` - `main` will be executed only once. `setInterval(main,1000)` - `main` will be executed every one second. –  Aug 11 '16 at 13:22