用于互联网 HTML 和 JS 速度测试的 Java 脚本错误结构

问题描述 投票:0回答:1

我试图让这个脚本工作,但是当我单击检查按钮时,它没有执行任何操作,脚本有问题,可能是在 while 循环中。这个想法是下载相同的图像 10 次并平均结果的下载速度。

document.querySelector('button').addEventListener('click', (e) => 
{
    var imageLink = 'https://upload.wikimedia.org/wikipedia/commons/3/3e/Tokyo_Sky_Tree_2012.JPG',
        downloadSize = 8185374,
        time_start, time_end,
        downloadSrc = new Image();
    document.querySelector('.loader-content').classList.add('hide');
    document.querySelector('.loader').classList.remove('hide');
    
    var j= 0;
    var FInalSpeed;
    
    while (j<10)
    {
    time_start = new Date().getTime();
    console.log(time_start
    var cacheImg = "?nn=" + time_start;
    downloadSrc.src = imageLink + cacheImg;
    console.log(downloadSrc);
    downloadSrc.onload = function () {
        //this function will trigger once the image loads
        time_end = new Date().getTime();
        var timeDuration = (time_end - time_start) / 1000;
            loadedBytes = downloadSize * 8,
            totalSpeed = ((loadedBytes / timeDuration) / 1024 / 1024).toFixed(2);
    FinalSpeed= FinalSpeed + totalSpeed;
    
        let i=0, speedOut;
        const animate = () => {
            if ( i < FinalSpeed ) {
                document.querySelector('.content').innerHTML = i.toFixed(2) + '<small>Mbps</small>';
                setTimeout(animate, 20);
                i+=1.02;
            } else {
                document.querySelector('.content').innerHTML = FinalSpeed + '<small>Mbps</small>';
            }
        }
        animate();

        document.querySelector('.content').innerHTML = FinalSpeed + '<small>Mbps</small>';
        document.querySelector('.loader-content').classList.remove('hide');
        document.querySelector('.loader-content').classList.add('result');
        document.querySelector('.loader').classList.add('hide');
        document.querySelector('.content').classList.remove('hide');
        e.target.innerText = 'CHECK AGAIN';
    }
})

我尝试改变循环,声明变量,而不是声明变量。但我找不到问题出在哪里,这似乎是一个基本结构问题。

javascript html while-loop cycle speed-test
1个回答
0
投票

这里有很多事情不好,我会告诉你我建议做什么,

  • 在这种情况下你应该使用 async 来在内部使用 await
  • finalSpeed设置为0强文本(以防万一未定义的操作...)
  • while 更改为 for,再次使用 async/await。
  • 添加等待该图像的承诺:)
  • 更快的下载跟踪速度
  • 以及处理错误(非常重要);)
  • 我还平均黎明负载的速度

代码应该如下所示:

// Changed to an async function to use await inside
document.querySelector('button').addEventListener('click', async (e) => {
    const imageLink = 'https://upload.wikimedia.org/wikipedia/commons/3/3e/Tokyo_Sky_Tree_2012.JPG';
    const downloadSize = 8185374;
    let FinalSpeed = 0; // Initialized FinalSpeed to 0 to fix undefined addition issue

    document.querySelector('.loader-content').classList.add('hide');
    document.querySelector('.loader').classList.remove('hide');

    // Changed while loop to for loop to use async/await for sequential downloads
    for (let j = 0; j < 10; j++) {
        const time_start = new Date().getTime();
        const cacheImg = "?nn=" + time_start;
        const downloadSrc = new Image();

        // Wrapped the onload event in a promise to await image loading
        await new Promise((resolve, reject) => {
            downloadSrc.onload = function() {
                const time_end = new Date().getTime();
                const timeDuration = (time_end - time_start) / 1000;
                const loadedBytes = downloadSize * 8;
                const totalSpeed = (loadedBytes / timeDuration) / 1024 / 1024;
                FinalSpeed += totalSpeed; // Accumulates speed for each download
                resolve(); // Resolve the promise once the image has loaded
            };
            downloadSrc.onerror = reject; // Handle image load errors
            downloadSrc.src = imageLink + cacheImg;
        });
        }
    
        FinalSpeed = (FinalSpeed / 10).toFixed(2); // Averages the speed after all downloads

        document.querySelector('.content').innerHTML = FinalSpeed + '<small>Mbps</small>';
        document.querySelector('.loader-content').classList.remove('hide');
        document.querySelector('.loader-content').classList.add('result');
        document.querySelector('.loader').classList.add('hide');
        document.querySelector('.content').classList.remove('hide');
        e.target.innerText = 'CHECK AGAIN'; // Ready for a new check
    });

测试它并告诉我它是否修复了您遇到的错误,

JavaScript 的名称中也没有空格 :p

© www.soinside.com 2019 - 2024. All rights reserved.