8

How can I use interval in js? For example I want to call a function every 5 seconds?

<script type="text/javascript">

setInterval(openAPage(), 5000);

function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://www.sabah.com.tr","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
</script>

This script doesn't work, anyone know why?

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
ramazan murat
  • 1,227
  • 1
  • 10
  • 8

3 Answers3

14

These answers are thorough and good; I just want to specifically fix yours. See the other answers for HOW/WHY.

setInterval(openAPage, 5000);

Note the lack of ().

Also, you're missing the closing } on the openAPage() function.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
4
setInterval(function(){
  /* your code here */
}, 5000);

And if you need to pass data to the function, you can do it with a closure:

setInterval(function(param){
  return function(){
    console.log(param);
  };
}("hello"), 5000);

will print "hello" to the console.

travelboy
  • 2,647
  • 3
  • 27
  • 37
3
setInterval(functionName, 5000)
The Scrum Meister
  • 29,681
  • 8
  • 66
  • 64