Javascript setTimeout function repeat

假装没事ソ 提交于 2019-12-29 09:05:45

问题


Is there a way to repeat a function in Javascript using the setTimeout function? For example, I need two functions to be called every five seconds. I have something like this:

$(document).ready(function(){    
    setTimeout('shiftLeft(); showProducts();', 5000);    
});

but it only happens once, five seconds after page loads, and I need it to happen every five seconds.


回答1:


Use setInterval() instead of setTimeout(), if you want your function to be executed repeatedly. setTimeout() delays the execution of your function for x seconds, while setInterval() executes your function every x seconds.

Both within the boundaries of the event queue of JavaScript, so don't be too confident, that you functions get executed at the exact time you specified

$(document).ready(function(){    
    setInterval( function(){ shiftLeft(); showProducts(); }, 5000);    
}); 



回答2:


Every x seconds can be done with setInterval:

$(document).ready(function(){    
  setInterval(function(){
    shiftLeft(); showProducts();
  }, 5000);    
});



回答3:


$(document).ready(function(){    
  setTimeout(function(){
    shiftLeft(); showProducts();
  }, 5000);    
});


来源:https://stackoverflow.com/questions/13268385/javascript-settimeout-function-repeat

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