javascript interval

喜你入骨 提交于 2019-12-28 04:26:11

问题


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?


回答1:


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.




回答2:


setInterval(functionName, 5000)



回答3:


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.



来源:https://stackoverflow.com/questions/4454430/javascript-interval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!