Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - 在Javascript中加入延迟(Put a Delay in Javascript)

I need to add a delay of about 100 miliseconds to my Javascript code but I don't want to use the setTimeout function of the window object and I don't want to use a busy loop.(我需要为我的Javascript代码添加大约100毫秒的延迟,但我不想使用window对象的setTimeout函数,我不想使用繁忙的循环。)

Does anyone have any suggestions?(有没有人有什么建议?)   ask by JGC translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Unfortunately, setTimeout() is the only reliable way (not the only way, but the only reliable way) to pause the execution of the script without blocking the UI.(不幸的是, setTimeout()是在不阻塞UI的情况下暂停脚本执行的唯一可靠方式(不是唯一的方法,但唯一可靠的方法)。)

It's not that hard to use actually, instead of writing this:(它实际上并不难,而不是写这个:) var x = 1; // Place mysterious code that blocks the thread for 100 ms. x = x * 3 + 2; var y = x / 2; you use setTimeout() to rewrite it this way:(你使用setTimeout()以这种方式重写它:) var x = 1; var y = null; // To keep under proper scope setTimeout(function() { x = x * 3 + 2; y = x / 2; }, 100); I understand that using setTimeout() involves more thought than a desirable sleep() function, but unfortunately the later doesn't exist.(我知道使用setTimeout()涉及比理想的sleep()函数更多的思考,但遗憾的是后者不存在。) Many workarounds are there to try to implement such functions.(有许多变通方法可以尝试实现这些功能。) Some using busy loops:(一些使用繁忙的循环:) function sleep(milliseconds) { var start = new Date().getTime(); for (var i = 0; i < 1e7; i++) { if ((new Date().getTime() - start) > milliseconds){ break; } } } others using an XMLHttpRequest tied with a server script that sleeps for a amount of time before returning a result .(其他人使用XMLHttpRequest与服务器脚本绑定,该脚本在返回结果之前会休眠一段时间 。) Unfortunately, those are workarounds and are likely to cause other problems (such as freezing browsers).(不幸的是,这些是解决方法,可能会导致其他问题(如冻结浏览器)。) It is recommended to simply stick with the recommended way, which is setTimeout() ).(建议简单地坚持使用推荐的方法,即setTimeout() )。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...