0

I wrote a script that will read in a text file and attempt to find duplicate entries in the dataset with the user-entered parameters. As the dataset is quite large, the page tends to freeze. I referenced this post here:

Prevent long running javascript from locking up browser

To perform my calculations in chunks using setTimeout(). I am trying to get a percentage complete to display on the page, but it won't display until the script finishes running (both Chrome and Firefox).

This is my pump function:

function pump(initDataset, dataset, output, chunk){
    chunk = calculateChunk(initDataset, dataset, output, chunk);
    document.getElementById("d_notif_container").style.display="block";
    document.getElementById("d_percent").innerHTML = NOTIF_SEARCH_START + percentComplete + "%"; //This is a div 
    document.getElementById("i_pc").value = percentComplete; //This is an input text field

    if(percentComplete < 100){
        console.log("Running on chunk " + chunk);
        setTimeout(pump(initDataset, dataset, output, chunk), TIMEOUT_DELAY);
    } 
    else {
        comparisonComplete(output);
    }
}

I attempted to display in two different ways, using innerHTML and value (two different elements). The percentComplete is a global variable that is updated in calculateChunk().

The strangest thing is, if I inspect one of those elements, I can watch the HTML change counting the percent (in Chrome). It just simply does not show on the actual page until the script is done running. I've tried changing the timeout up to 1000 as well with not luck.

Any idea why this is happening?

Community
  • 1
  • 1
rphello101
  • 1,583
  • 4
  • 28
  • 56

1 Answers1

2

This code

setTimeout(pump(initDataset, dataset, output, chunk), TIMEOUT_DELAY);

calls pump and passes its return value into setTimeout, exactly the way foo(bar()) calls bar and passes its return value into foo.

If you want to call pump after a timeout with those values, you can use Function#bind to do it:

setTimeout(pump.bind(null, initDataset, dataset, output, chunk), TIMEOUT_DELAY);
// ------------^^^^^^^^^^

Function#bind returns a new function that, when called, will use the given this value (the first argument) and arguments you give bind.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
  • Works perfectly. Thanks. A note to anyone else that looks at this: don't forget "null". Screws up the data you pass in if you do... – rphello101 Jun 27 '16 at 18:10