在javascript while循环中作为条件返回true [英] true as a condition in a javascript while loop

查看:154
本文介绍了在javascript while循环中作为条件返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这段代码会导致浏览器崩溃:

I was wondering why this code crash my browser:

while (true) {
    $('.selector')
        .animate({ 'bottom': '30px' }, 500)
        .animate({ 'bottom' : '20px' }, 500);
}

和其他代码有效(无条件)

and this other code works (without true as a condition)

var a = 0;
while (a < 1000) {
    $('.selector')
        .animate({ 'bottom': '30px' }, 500)
        .animate({ 'bottom' : '20px' }, 500);
    a++;
}

如果我自己敢回答这个问题,我会说第二个代码填充了1000个动作的队列,并在第一个动作没有完成并导致浏览器崩溃时停止。

我需要它是无限的,但直到动画完成后才进行下一个迭代。我在这里到处玩 stop(); ,但没有成功。

If i would dare to answer the question myself i'd say that the second code fill a queue of 1000 actions and stops when the first one never finishes and crash the browser.
I need it to be infinite but not going to the next iteration until the animations are complete. I was playing with stop(); here and there but it didn't do the trick.

推荐答案

如果要尝试执行我认为要执行的操作,请尝试考虑使用 window.setInterval

If you're trying to do what I think you're trying to do, try considering using window.setInterval

https:// developer .mozilla.org / zh-CN / docs / Web / API / WindowOrWorkerGlobalScope / setInterval

while(true)永远运行!它永远不会停止。

while(true) just runs forever! It never stops.

要解释为什么永远运行的循环会使浏览器崩溃,请考虑以下示例:

To explain why a loop that runs forever crashes the browser, consider the following example:

Joe每秒可以执行1000条命令。您的讲话速度很快,因此每秒可以给Joe一百万个命令。如果您给Joe 7000(将花费您7毫秒)命令并停止,Joe将花7秒执行它们并停止。

Joe can execute 1000 commands per second. You are a fast speaker, so you can give Joe a million commands per second. If you give Joe 7000 (will take you 7 milliseconds) commands and stop, Joe will take seven seconds to execute them and stop.

现在,想象一下当您给Joe时会发生什么无限数量的命令(例如 while(true) ...... Joe将永远无法追上您,因为您一直在给他命令,而他不能

Now imagine what happens when you give Joe an infinite number of commands (as in a while(true)... Joe will never be able to catch up to you since you keep giving him commands and he can't process them all, his brain will start to hit him, and he won't be as responsive, if responsive at all.

您的浏览器是Joe。它运行在单线程(一个内核),资源有限,开销非常大,并且运行的是处理器效率相对较低的语言(Javascript)。

Your browser is Joe. It runs on a single thread (one core), has limited resources, very high overhead, and runs a relatively very processor-inefficient language (Javascript).

技术上讲准确的考虑处理器的工作原理,但应该可以理解这一点。

This analogy isn't the most technically accurate one considering how processors work, but it should get the point across.

这篇关于在javascript while循环中作为条件返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆