为什么简单的处理代码会导致浏览器崩溃?

问题描述

在 p5.js 中,我写了一个简单的线性循环,它在屏幕上的随机点之间画线。

如果我循环 99 999 次,屏幕会立即显示

999 999 次,耗时十秒

9 999 999 它会挂起浏览器。

为什么在具有基本操作的线性循环中会发生这种情况?处理生命周期有什么我不理解的地方吗?就像画布何时更新(每行或分批或什么)?我需要将我的代码放在异步循环中吗?

function setup() 
{
    createCanvas(1920,965,P2D);
    colorMode(HSL,100); // hue saturation lightness
    noLoop();
    background(100,100,255); //solid white background           
    for (let i = 0; i < 9999999; i++)
        drawLines()
}

function drawLines() 
{
    stroke(60,random(60,100),random(0,255);
    const p1 = getRandomPoint();
    const p2 = getRandomPoint();
    line(p1.x,p1.y,p2.x,p2.y);
}

function getRandomPoint()
{
    return { x: random(0,width),y: random(0,height) };
}

解决方法

9999999 只是一次多行。拆分绘制线条:

`from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
list=[]
chrome_options = Options()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver = webdriver.Chrome(options=chrome_options)
driver.get("https://typetest.io/")
element = driver.find_element_by_id("test-input")
element.sendKeys("Hello")`
function setup() 
{
    createCanvas(1920,965,P2D);
    colorMode(HSL,100); // hue saturation lightness
    background(100,100,255); //solid white background       
}
 
function draw()
{  
    for (let i = 0; i < 1000; i++)
        drawLines()
    if (frameCount >= 9999)
        noLoop();     
}

function drawLines() 
{
    stroke(60,random(60,100),random(0,255);
    const p1 = getRandomPoint();
    const p2 = getRandomPoint();
    line(p1.x,p1.y,p2.x,p2.y);
}

function getRandomPoint()
{
    return { x: random(0,width),y: random(0,height) };
}