在运行jquery之前从5开始倒计时

Count down from 5 before running jquery

本文关键字:开始 倒计时 运行 jquery      更新时间:2024-05-13

我有一个jQuery相机插件,它使用以下命令拍摄快照。

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

这是它运行的代码。

<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>

我正在寻找一个从5开始倒计时的解决方案,然后在它达到0时拍摄快照。现在,当有人点击按钮时,它会立即拍照。该解决方案不一定很花哨,但应该向用户指示它从5开始倒计时。

您需要了解setTimeout,它允许您在一定时间后调用函数或执行代码段。

在您的情况下,可以使用window.setTimeout包装Webcam.snap函数。

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>