如何在x秒后停止运行Javascript函数? [重复]

This question already has an answer here:

I have a specific sweet alert on my website that I use for my div class that opens with onclick, but I want this onclick alert to stop after 60 seconds for example. So after 60 seconds the alert won't show up if I click the div.THis is what I got so far

<script type="text/javascript">
function JSalert(){
    swal("Error", "You have to watch the video first.", "error");
}
</script>


<div class="blocked" onclick="JSalert()">
</div>

As I understand the question (and based on the translated text in the alert) :

  • Give a warning if the user clicks the div
  • after 60seconds (an eternity in web time (5s here for testing)) then don't show the alert when they click

(From OPs: "after 60 seconds the alert won't show up if I click the div" or, put another way, "the alert won't show up if I click the div after 60 seconds")

var showalert = true;
setTimeout(function() { showalert = false; }, 5000);  /* 5s for testing */

function JSalert(){
  if (showalert) {
    alert("Please don't click too soon");
  }
}
<div class="blocked" onclick="JSalert()">click me, but not too soon</div>

This could be improved using data- attributes / jquery .data(), but the concept is the same.

</div>

What you lookin for is setTimeout: https://www.w3schools.com/jsref/met_win_settimeout.asp

Something like that in your JSalert function:

setTimeout(function() {
    // close modal here
}, 60000);

Or check the sweet alert docs there's also a timer: https://sweetalert.js.org/docs/#timer