Why does setTimeout and setInterval run too fast? [duplicate]

南笙酒味 提交于 2020-12-15 20:22:52

问题


function process(){
  window.location.reload(false);
}

function looping(){
  setTimeout(process(), 10000);
}

var looper = setInterval(looping(), 10000);

I'm trying to reload a page every 10 seconds, but the above code will too frequently reload the page. Why?


回答1:


function process(){
  window.location.reload(false);
}

function looping(){
  setTimeout(process, 10000);
}

var looper = setInterval(looping, 10000);

try above code.

in your example, instead of providing a call back function to the setTimeout and setInterval, you were, just calling the callback function. just provide the function name and its fixed

UPDATE: Functions are first class objects in JS. you can pass it to a function, return a function from another function etc... so those things are done, by just using the function name(just the function name, like any other variable name). invoking a function is done using the parenthesis, you were by mistake invoking the function, instead of passing the function to setTimeout

and you can get rid of the setTimeout completely and just do as shown below

function process(){
      window.location.reload(false);
}       

var looper = setInterval(process, 10000);  



回答2:


The problem with your code is, you are invoking the function instead of passing it to be called after the time interval. If you need to pass the function, just pass the name of the function. Putting the parentheses is actually invoking the function which will happen right away the moment you set the setInterval

If you want to reload your page every 10 seconds, you can simplify it a bit. I don't see any reason why you should have setInterval in this case. I think this is sufficient and should work

// After 10s, run the function
setTimeout(function() { window.location.reload(false)},10000)

You might want the 10s counted after all the DOM is ready.

var fn = function() { 
  setTimeout(function() { window.location.reload(false)},10000);
}

// Note that, I pass the function name instead of invoking it with fn()
document.addEventListener('DOMContentLoaded', fn)

The reason why I am using setTimeout instead of setInterval is, it will only run once per session and will be refreshed. I think it should be sufficient.




回答3:


process() this will call function and process will return function. Hence your function is called immediately.

try

setTimeout(process,10000)



来源:https://stackoverflow.com/questions/34987427/why-does-settimeout-and-setinterval-run-too-fast

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