javascriptpythondjangowhile-looppython-rq

JavaScript while loop + setInterval doesn't work in Django


I'm developing a website using Django. I have about 50 functions. And it takes about 1 minute to get the result for all of them.

The problem is that I use heroku for my app. And heroku has a limit of 30 sec to get the request. I was suggested to use background tasks. Now I am using background jobs in Python RQ. For each function I made a separate task in Views. Here is an example of one of the tasks:

task_robots_url = q.enqueue(Robots(url).get_url)
robots_url = task_robots_url.result

And now I need to check whether the job is finished in the Template. And when it's finished, display the result.

I want to check with JS each second whether the job is finished. If it's not finished - show "Loading ... " message to the user. If it's finished - show the result.

Here is my JS code:

  <script>
    var h1 = document.getElementById("h1");
    var job_result = "{{ robots_url }}"

    var test = function () {
      if (job_result ==  "") {
          h1.innerText = "Waiting...";
          } else if (job_result == "None") {
          h1.innerText = "Waiting ...";
          } else if (job_result == undefined) {
          h1.innerText = "Waiting ...";
          } else { 
          clearInterval(inter);
          h1.innerText = job_result; 
          }
      }
    var inter = setInterval(test, 1000);
  </script>

But this doesn't work. When the result page starts - I've got an empty result. And it displays Waiting. Then I have None result. And it still displays Waiting. But now after waiting there is no result.

In the documentation for Python RQ it is said I should put time.sleep() for several seconds in my code. And if I put time.sleep(2) - I got the result. But if I put time.sleep(2) for each of my 50 functions - I will get 100 sec. And the limit in Heroku is only 30 sec... So I need to check and display the result without sleep()...


Solution

  • The setInterval() method calls a function or evaluates an expression at specified intervals (in milliseconds).

    The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.

    You are calling setInterval so many times which cause your browser to crash eventually.

    assuming job_result value changes after 10 sec you can write the following code:

    var job_result = {{ job_result }};
    
    var loadingMessage = function (){
        if (!job_result) {
            document.write("Loading ...");
        }
        else {
            return
        }
    }
    
    setInterval(() => loadingMessage, 1000);
    

    You can call return to stop the Interval for running or you can use setTimeout and to call a function that clears the interval