0

I have a jQuery camera plugin that uses the following command to take a snapshot.

<img id="camera_icon" src="images/icons/camera-icon2.png" onClick="take_snapshot()">

Here is the code it runs.

<script language="JavaScript">
function take_snapshot() {
    // take snapshot and get image data
    Webcam.snap( function(data_uri) {
        // display results in page
        document.getElementById('results').innerHTML = 
            '<h2>Saved Snapshot</h2>' + 
            '<img src="'+data_uri+'"/>';

        Webcam.upload( data_uri, 'save_snapshot.php', function(code, text) {
            // Upload complete!
            // 'code' will be the HTTP response code from the server, e.g. 200
            // 'text' will be the raw response content
        }); 
    });
}
</script>

I am looking for a solution that will count down from 5, and then take a snapshot when it reaches 0. Right now, when someone clicks the button, it will instantly take the picture. The solution doesn't have to be fancy, but should indicate to the user that it's counting down from 5.

Pang
  • 9,564
  • 146
  • 81
  • 122
Jeff F
  • 25
  • 3

1 Answers1

1

You'll want to look at setTimeout, it allows you to call a function or execute a code snippet after a set amount of time.

In your case, you can wrap the Webcam.snap function with window.setTimeout.

function take_snapshot() {

    var timer = document.getElementById('shutter');
    timer.setAttribute("disabled", "disabled");
    timer.innerHTML = 5;

    var countdown = window.setInterval(function() {
    var seconds = timer.innerHTML;
    seconds = seconds - 1;
    timer.innerHTML = seconds;

    if (seconds == 0) {
      timer.innerHTML = "Take Pic";
      timer.removeAttribute("disabled");
      clearInterval(countdown);
    }
  }, 1000);

  window.setTimeout(function() {

    // Run your code here

  }, 5000);
}
button {
  width: 80px;
  height: 80px;
  border-radius: 40px;
  font-size: 14px;
}
<button onClick="take_snapshot()" id="shutter">Take Pic</button>
<div id="timer"></div>
Brett DeWoody
  • 59,771
  • 29
  • 135
  • 184
  • Thanks. Do you know how I can incorporate an actually countdown for the user to see or point me in the right direction. Thank You. – Jeff F Apr 12 '16 at 04:24
  • Here's a [pen](http://codepen.io/brettdewoody/pen/vGdaQK) with more details. The basic idea is to use `setInterval` to create a countdown and display the countdown on the page. In my example I've chosen to display the countdown in the button. – Brett DeWoody Apr 12 '16 at 05:01
  • I didn't use jQuery in the example but you could replace some of the selectors with jQuery if you wanted, namely `var timer = $('#timer');`, then `timer.attr('disabled', 'disabled')` and `timer.removeAttr('disabled')`. – Brett DeWoody Apr 12 '16 at 13:23