js USES setTimeout to implement the time bomb approach

  • 2020-05-27 04:22:08
  • OfStack

This article illustrates an example of how js USES setTimeout to implement a time bomb. Share with you for your reference. The specific analysis is as follows:

Looking at the css discovery blog today, there was a time bomb effect with setTimeout, and I drew a cat and wrote one myself.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312"/>
<title> Headless document </title>
<style>
div{
width:200px;
height:50px;
margin:30px auto 0;
background:#ccc;
text-align:center;
font:14px/50px arial;
cursor:pointer
}
</style>
<script type="text/javascript" src="js/jquery_1.4.2.js"></script>
</head>
<body>
<div id="zha"> Start timing </div>
<div id="chai" style="display:none"> Disarm bombs </div>
<script>
$("#zha").bind("click",function(){
 zha();
})
$("#chai").bind("click",function(){
 chai();
})
var time = 5;
var timer = 0;
function zha(){
 var text = " The countdown ";
 text += time--;
 $("#zha").text(text);
 if(time >=0){
  timer = setTimeout(zha,1000);
  $("#zha").css("color","black");
  $("#chai").show();
 }else{
  $("#zha").text(" The explosion ");
  $("#zha").css("color","red");
  time = 5;
  $("#chai").fadeOut();
 }
}
function chai(){
 clearTimeout(timer);
 $("#zha").text(" Bomb defused , Click to continue ");
}
</script>
</body>
</html>

I hope this article has helped you with your javascript programming.


Related articles: