Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript interval

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?

like image 636
ramazan murat Avatar asked Dec 15 '10 20:12

ramazan murat


People also ask

What is interval in JavaScript?

Definition and Usage. The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

What are the types of time intervals in JavaScript?

JavaScript offers two timer functions setInterval() and setTimeout(), which helps to delay in execution of code and also allows to perform one or more operations repeatedly.

What is interval in TypeScript?

setInterval() will evaluate expressions or calls a function at certain intervals. This method will continue calling function until window is closed or the clearInterval() method is called and returns a non-zero number which identifies created timer or a numeric value.

Does JavaScript have a timer?

JavaScript provides two functions to delay the execution of tasks. These are timer functions.


3 Answers

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.

like image 64
Surreal Dreams Avatar answered Nov 16 '22 09:11

Surreal Dreams


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.

like image 32
travelboy Avatar answered Nov 16 '22 11:11

travelboy


setInterval(functionName, 5000)
like image 36
The Scrum Meister Avatar answered Nov 16 '22 09:11

The Scrum Meister