The timer allows the JS effect to execute once every few seconds or after n seconds to perform an effect. Timers do not belong to JavaScript, and are features provided by the Window object.
SetTimeout usage:
Window.settimeout (' statement ', MS); // executes a statement after a specified millisecond
Cases
<! DOCTYPE html> #div1 { width:300px; height:300px; Background:blue; Border-bottom:1px solid black; } </style> function Change () { document.getElementById ("P"). InnerHTML = "replaced"; } Window.settimeout (//3 seconds to execute change method </script> </body></ Html>
Optimization: Timer effect plus countdown effect
SetInterval (' statement ', MS); Execute once every specified millisecond
To clear the timer:
Clearinterval (); and cleartimeout ();
Code
<! DOCTYPE html>#div1 {width:300px; height:300px; Background:blue; Border-bottom:1px solid black; } </style>functionChange () {varINP = Document.getelementsbyname ("Time") [0]; varTime = parseint (inp.value)-1; Inp.value=Time ; if(Time = = 0) {document.getElementById ("P"). InnerHTML = "replaced"; Clearinterval (clock); //Clear Timer } } varClock = setinterval ("Change ()", 1000);//executes once per second</script> </body>"Example" if setinterval is not applicable, use only setTimeout to achieve the effect of performing once every time
Using SetTimeout to achieve setinterval effects
<! DOCTYPE html>#div1 {width:300px; height:300px; Background:blue; Border-bottom:1px solid black; } </style>varClock =NULL; functionChange () {varINP = Document.getelementsbyname ("Time") [0]; varTime = parseint (inp.value)-1; Inp.value=Time ; if(Time = = 0) {document.getElementById ("P"). InnerHTML = "replaced"; Cleartimeout (clock); return; } setTimeout ( "Change ()",); } varClock = setTimeout ("Change ()", 1000);//executes once per second</script> </body>Javascript notes and summaries (2-13) Timers SetTimeout and SetInterval