如何在javascript中使循环等待代码执行x周期?
基本上,我希望每5秒钟在一个永无止境的循环中执行一个函数 我尝试了很多事情,但都失败了,例如: #1:如何在javascript中使循环等待代码执行x周期?,javascript,jquery,Javascript,Jquery,基本上,我希望每5秒钟在一个永无止境的循环中执行一个函数 我尝试了很多事情,但都失败了,例如: #1: while(1){ setTimeout(function(){ executeThis(); },3000); console.lop("This is to text that loop has stopped till executeThis function have been finished");} setTimeout(function(){ while(1
while(1){ setTimeout(function(){ executeThis(); },3000); console.lop("This is to text that loop has stopped till executeThis function have been finished");}
setTimeout(function(){ while(1){executeThis();} },3000);
虽然executeThis()
会在3秒后被调用,但与此同时,循环不断执行console.log()
数万次,导致浏览器崩溃
#2:
while(1){ setTimeout(function(){ executeThis(); },3000); console.lop("This is to text that loop has stopped till executeThis function have been finished");}
setTimeout(function(){ while(1){executeThis();} },3000);
这个只需继续调用executeThis()并再次崩溃浏览器
有没有更好的方法在x秒后调用my函数并使循环停止执行,直到函数完成?setInterval将完成此工作
//sends hello every half sec.
setInterval(function(){console.log('hello');}, 500);
这回答了你的问题吗?好的,不用了,谢谢