What are the basic uses of JavaScript setTimeout of

  • 2021-09-12 00:24:33
  • OfStack

When making dynamic effects of web pages, you may encounter the need to delay the execution. At this time, you can use the timer in js to realize such requirements. This article will summarize the usage of setTimeout ().

The setTimeout () method is used to call a function or evaluate an expression (in milliseconds) after a specified number of milliseconds setTimeout () only executes the function once. If you need to call it more than once, you can use setInterval () or call setTimeout () again in the function body

Usage of setTimeout ()

Give a simple example

Add the following code, and after waiting for 3 seconds on the open page, a warning box "Hello" will pop up


<script>
  setTimeout("alert(' How do you do ')", 3000) 
</script>

Effect:

A more complicated definition of function


<script>
var myvar;

function myFunction() {
  myVar = setTimeout(alertFunc, 3000);
}

function alertFunc() {
 alert("Hello!");
}

function that automatically adds 1 per second

Use setTimeout () to increase the value of the text box by 1 every second. Of course, you can also set other increment rates, such as adding 5 every 5 seconds or adding 1 every 5 seconds.


<script>
x = 0
function countSecond( )
{   x = x+1
    document.fm.displayBox.value=x
    setTimeout("countSecond()", 1000)
}
</script> 
<body bgcolor=lightcyan text=red> <p> </br>
<form name=fm>
<input type="text" name="displayBox"value="0" size=4 >
</form>
<script>
countSecond( )
</script>
</body> 


Using the above method to set the time, although setTimeout () is set to be 1 second, the browser has two other functions to perform, so the time of one loop is slightly more than 1 second, for example, there may be only 58 loops in one minute.

Delayed closure of web pages

Press the button, Window open () opens a web page, executes the command, and automatically closes after 3 seconds


<button onclick="openWin()"> Open  " Window "</button>
<script>
function openWin() {
  var myWindow = window.open("", "", "width=200, height=100");
  myWindow.document.write(" This is 1 New windows ");
  setTimeout(function(){ myWindow.close() }, 3000);
}
</script>

Cancel setTimeout ()

When an setTimeout () starts the loop, we want to stop it by using clearTimeout ()


<button onclick="myFunction()"> Click me to pop up </button>
<button onclick="myStopFunction()"> Prevent ejection </button>
<script>
var myVar;
function myFunction() {
  myVar = setTimeout(function(){ alert("Hello") }, 2000);
}
function myStopFunction() {
  clearTimeout(myVar);
}
</script>

Summary

setTimeout (), clearTimeout (), setInterval () can flexibly use their characteristics in the process of writing code to achieve the purpose that needs to be accomplished


Related articles: