JavaScript realizes time countdown jump of recommendation

  • 2021-07-01 06:21:57
  • OfStack

1. The setTimeout () method is used to call a function or evaluate an expression after a specified number of milliseconds.

setTimeout () only executes code once. If you want to call more than once, use setInterval () or have code itself call setTimeout () again.


<!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 runat="server"> 
<title>setTimeout</title> 
</head> 
<body> 
<div id='div1'> </div> 
</body> 
</html> 
<script type="text/javascript"> 
// Set the reciprocal number of seconds  
var t = 10; 
// Display reciprocal seconds  
function showTime(){ 
t -= 1; 
document.getElementById('div1').innerHTML= t; 
if(t==0){ 
location.href='http://www.baidu.com'; 
} 
// Execute per second 1 Times ,showTime() 
setTimeout("showTime()",1000); 
} 
// Execute showTime() 
showTime(); 
</script> 

2. The setInterval () method calls a function or evaluates an expression at a specified period (in milliseconds).

The setInterval () method keeps calling the function until clearInterval () is called or the window is closed. The ID value returned by setInterval () can be used as an argument to the clearInterval () method.


<html>
<body>
<input type="text" id="clock" size="35" />
<script language=javascript>
var int=self.setInterval("clock()",50)
function clock()
{
var t=new Date()
document.getElementById("clock").value=t
}
</script>
</form>
<button onclick="int=window.clearInterval(int)">
Stop interval</button>
</body>
</html>

Let's introduce the related reading below

1. The setInterval () function can be found in section 1 of the setInterval () function.

2. location. href See the href Properties 1 section of the Location object.

3. The innerHTML attribute can be found in the Usage of the innerHTML attribute section 1 of js.

The following is an example (example):


<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>js Method of jumping pages regularly </title> 
</head> 
<body> 
<script type="text/javascript"> 
var t=10;// Set the time of jump  
setInterval("refer()",1000); // Start 1 Second timing  
function refer(){ 
if(t==0){ 
location="www.baidu.com"; //# Set the link address of jump  
} 
document.getElementById('show').innerHTML=""+t+" Jump after seconds "; //  Show countdown  
t--; //  Counter decrement  
} 
</script> 
<span id="show"></span> 
</body> 
</html> 

Problems encountered:

When the above js method is placed in $(function () {......}), the browser will report methodXX () is not defined;

The definition of function () {} should be placed in < script > < /script > Medium


Related articles: