基本上,我想每5秒在一个永不结束的循环中执行一个函数。
我尝试了很多事情,但都失败了
#1:
while(1){ setTimeout(function(){ executeThis(); },3000); console.lop("This is to text that loop has stopped till executeThis function have been finished");}
虽然executeThis()
会在3秒钟后被调用,但与此同时,循环会持续执行console.log()
成千上万次,这会导致浏览器崩溃。
#2:
setTimeout(function(){ while(1){executeThis();} },3000);
这个只是不断地调用executeThis()
,然后再次崩溃浏览器。
有没有更好的方法可以在x秒后调用我的函数,并使循环停止执行,直到函数完成?
setInterval将完成的工作
//sends hello every half sec.
setInterval(function(){console.log('hello');}, 500);