The difference between setTimeout of and setInterval of methods

  • 2020-03-30 01:05:12
  • OfStack

SetTimeout () and setInterval() are both functions of js's timing function.

SetTimeout () :

In the js manual: used to call a function or evaluate an expression after a specified number of milliseconds;

That is, execute after the set number of seconds.

Experiment code (change the body background color) :
 
setTimeout(function(){ 
$("body").css("background","red"); 
},5000); 

SetInterval () :

As explained in the js manual: call a function or evaluate an expression for a specified period (in milliseconds). Call the function until clearInterval() is called or the window is closed.

Execute your own effect code or function in the number of seconds you set.

Experiment code (several seconds experiment) :
 
<div class="clock"></div> 
<script> 
var num = 0; 
setInterval(function(){$(".clock").html(num++)},1000); 
</script> 

Conclusion:

The setTimeout() method executes the function after waiting for the specified time and executes the incoming handle function only once.

The setInterval() method executes the incoming handle function after each specified interval, looping until the window or clearInterval() is closed.

Related articles: