In JavaScript setInterval and setTimeout method

The window object in an HTML document, with many commonly used method, which is similar to the use of two methods for the setInterval () and setTimeout () method:

1.setInterval()

The specified period (in milliseconds) to the calling function or calculation expression. A setInterval () ID is used as a parameter value returns the clearInterval () method.

Date use the following built-in objects to demonstrate the effect of this method:

In this section of the code, the test () method passing the argument list name setInterval method, and set the interval time is 1000 milliseconds long, meaning that every second print the current time information:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			
			function test(){
				var date = new Date();
				var hour = date.getHours();
				var minute = date.getMinutes();
				var second = date.getSeconds();
				var current = hour+":"+minute+":"+second;
				console.log(current);
			}
			
			var id = setInterval("test()",1000);
		</script>
		
		<span οnclick="test()">点我</span>
	</body>
</html>

 

2.setTimeout()

The method of action is: a function call after a specified number of milliseconds or calculation expression. A setTimeout () ID is used as a parameter value returns the clearTimeout () method.

The following built-in objects or using Date to demonstrate the effect of this method:

In this section of the code, the test () method passing the argument list name setTimeout method, and set the interval time is 5000 milliseconds long, meaning that the method will be executed after 5 seconds, the time the first printed information 16 : 20: 39, and the time output process statement execution after 5 seconds Test (), the second time information is 16:20:44 printing.

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<script>
			var date = new Date();
			var hour = date.getHours();
			var minute = date.getMinutes();
			var second = date.getSeconds();
			var current = hour+":"+minute+":"+second;
			console.log(current);
			function test(){
				console.log("到我了");
				date = new Date();
				hour = date.getHours();
				minute = date.getMinutes();
				second = date.getSeconds();
				current = hour+":"+minute+":"+second;
				console.log(current);
			}
			
			var id = setTimeout("test()",5000);
		</script>
		
		<span οnclick="test()">点我</span>
	</body>
</html>

There is also mentioned the clearInterval () method and the clearTimeout () Method:

clearInterval (): cancel timeout by the setInterval () settings.

clearTimeout (): cancel the timeout set by setTimeout () method.

Published 99 original articles · won praise 93 · views 5223

Guess you like

Origin blog.csdn.net/DangerousMc/article/details/102957581