Two methods JavaScript timers

JavaScript timer has the following two methods:

setInterval (): the specified period (in milliseconds) to the calling function or calculation expression. The method will continue to call the function, until the clearInterval () is called, or the window is closed. setInterval () function is used as follows:

the setInterval () ( "call the function", "the time between the periodic execution or calling code interval"),

function hello () {alert ( " hello");}
Repeats a method:

var t1= window.setInterval(“hello()”,3000);

The method of removing the timer
window.clearInterval (t1);

setTimeout (): calling function or the calculation expression after a specified number of milliseconds.

setTimeout () function usage such as: setTimeout ( "function call", "number of milliseconds to wait before executing the code.")

Only once, for 3 seconds to display a pop: var t = setTimeout (function () {alert ( "Hello")}, 3000)

We need to achieve the cycle call setTimeout timer function written in the called function inside. as follows:

function show(){

alert(“Hello”);

var myTime = setTimeout(“show()”,1000);

}

Off Timer Usage: clearTimeout (MyTime);

Wherein, myTime is setTimeout () function returns a timer object.

From a performance point, if the code is aimed at constantly running, you should not use setTimeout, but should use setInterval, setTimeout because every time there will initialize a timer, while setInterval will initialize a timer at the beginning.

Published 11 original articles · won praise 16 · views 403

Guess you like

Origin blog.csdn.net/weixin_43894771/article/details/104747806
Recommended