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:
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.
Then 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 + '●' 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: ●
- 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.
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 ...