Search code examples
javascripthtmlwhile-loopcyclespeed-test

Java Script for an internet HTML and JS speed test wrong structure


I am trying to get this script to work, but when I click the check button, it doesn't do anything, there is something wrong with the script, probably in the while cycle. The idea is to download the same image 10 times and average the resulted download speed.

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';
    }
})

I tried changing the cycle, declaring the vars, not declaring the vars. But I can't find where the issue is comming from, it seems to be a basic structure problem.


Solution

  • there are a lot of things going bad here, i'll tel you what i recommend doing,

    • you should use async in this case to use await inside
    • set finalSpeed to 0 strong text(just in case undefined actions...)
    • change from while to for, again to use async/await.
    • add a promise to await for that image :)
    • better speed download tracking
    • and handling errors (very important) ;)
    • also i avarage the speed of the dawnload

    the code should look like this:

    // 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
        });
    

    Test it and tell me if it fixed the errors you've got,

    also JavaScript has no spaces on the name :p