Quantcast
Channel: Bob Belderbos » Web development
Viewing all articles
Browse latest Browse all 11

Better alternative for PHP sleep: use a dotted progress bar with Javascript

0
0

Last week I developed a playing/upcoming movie HTML newsletter. I just added a feature to add the movies to your watch list on sharemovi.es. You have to be authenticated to FB. If not I am redirecting from the adder script to the main page:

Screen Shot 2015-11-19 at 22.33.35

The problem with PHP sleep

This taught me a cool trick: you need to pause a bit so the user can read the message before being redirected. My first approach was PHP’s sleep function, but that would show the initial echo only after the sleep, rendering it useless.

javascript_dotted_progress_barThen I read about ob_start() and ob_flush(). This did not work either, reason: browsers also contain their own buffers. I realized that apart from sleeping I wanted to show some sort of progress bar.

Here we enter JavaScript which is great for this kind of asynchronous stuff. I used this solution. As explained at w3schools: “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”.

Code:

    <script>
    var div = document.getElementById('wait');
    var counter = 0;
    var waitSecs = 8;
    var refreshId = setInterval(function () {
      ++counter;
      div.innerHTML = div.innerHTML + '&#x25cf;'
      if(counter == waitSecs){
        clearInterval(refreshId);
        top.location.href='http://sharemovi.es'
      }
    }, 1000);
    </script>

Notes:

  • See a demo of this script here.
  • I put an empty #wait div in the html and get it with document.getElementById, this element is used to append progress elements to.
  • I choose dots for progress, but I probably redo it with a count down which is more cooler, I choose a bigger dot = html encoding: &#x25cf;
  • setInterval does something for every interval (here 1 sec = 1000 ms), until waitSecs = 8 seconds, then it stops the loop by calling clearInterval and redirects to the sharemovi.es homepage (top.location.href).
  • An enhancement could be to redirect to FB login page directly but it could surprise users, hence the feedback loop.

Screen Shot 2015-11-19 at 22.33.39


Two more comments:

1. to learn to code: practice, fail, get better by doing, it takes time and effort. This is a small feature, but it taught me a few valuable things about PHP and Javascript. Follow Alec Baldwin’s ABC: always be closing and replace closing by coding :)

2. the featured image for this and last 2 posts were made with a new webtool I built: CSS Featured Image Creator. I will write a blog post about it soon, it is still work in progress …


Viewing all articles
Browse latest Browse all 11

Latest Images

Trending Articles





Latest Images