Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How does setinterval work in js? How do you stop setinterval?


May 06, 2021 JavaScript with HTML DOM Reference book


Table of contents


() function that is called regularly and can be called or evaluated in milliseconds for the specified period of time. 30> () T he effect is to call functions, methods, or objects every once in a while while the animation is playing. ows: he ID value returned by setInterval() can be used as an argument to the clearInterval() method. The syntax format of the setInterval action is as follows:


setInterval(function,interval[,arg1,arg2,...... argn])
setInterval(object,methodName,interval[,arg1,arg2,..... argn])


The next two parameter codes are your js code, and millisec is the interval, in milliseconds. /b20> The first format is the default syntax for setInterval functions in the standard action panel, and the second format is the method used in expert mode actions. /b11> The argument fusion is a function name or a reference to an anonymous function. T he object parameter specifies the object derived from the Object object. M ethodName develops the method to be called in the object parameter.


Interval develops the time between calls to function or methodName in milliseconds. The rear arrg1 and so on are optional parameters for setting parameters passed to fusion or methodName.


How does setinterval work in js? How do you stop setinterval?

SetInterval calls the function at intervals as close as possible to interval when it sets a time interval that is less than the animation frame rate (e.g., 10 frames per second, equivalent to 100 milliseconds). en. f the interval is greater than the animation frame rate, it is called only after each playhead enters a frame to reduce the impact of each refresh screen.


The following example calls an anonymous function every 1 second.


setInterval (function)(trace ("I'll show it every 1 second"), 1000); //) function here is a function without a function name. Becomes an anonymous function, followed by 1000 time intervals in milliseconds.

function show1(){
    trace("每隔1秒显示一次");
}
function show2(str){
    trace(str);
}
setInterval(show1,1000);
setInterval(show2,2000,"每隔2秒我就会显示一次");
The setInterval method of the function has been described above. Let's look at the setInterval method for objects.


First, write an example of a setInterval method that calls an object in an action, which does not require passing parameters.

myobj=new Object();//创建一个新的对象
myobj.interval=function){
    trace("每隔1秒显示一次");
}//创建对象的方法。
setInterval(myobj,"interval",1000);//设定时间间隔调用对象的方法。
Let's show you how to pass parameters. In fact, the truth is the same as the passing parameters of the function.
myobj=new Object();
myobj.interval-function(str){
    trace(str);
}
setInterval(myobj,"interval",2000," 每隔2秒我就会显示一次");
Note. T o call a method defined for an object, you must use the second syntax format in expert mode. /b10> In this case, let's make a dynamic display of time screen. T his can be done with the following code.
setInterval(show,1000);
function show(){
    time=new Date();
    hour=time.getHours();
       minu=time.getMinutes();
       sec=time.get.Seconds();
    datetime=hour+":"+minu+":"+sec;
}//这里的datetime是一个动态文本框的变量名字。

Stop setinterval with the clearinterval command

Intervals can be created with the setInterval command and terminated with the clearInterval command. T here are two formats for the parameters used by setInterval. I n the first format, the arguments you pass to setInterval can be a function name, intervals over time, and some related parameters passed to the previous function. W hen setInterval runs, it passes the listed parameters to the specified function at specified intervals until you call clearInterval to terminate them. T he relevant demonstration code is as follows:

function show(){ 
trace("每隔一秒我就会显示一次"); 
} 
var sh; 
sh=setInterval(show,1000); 
clearInterval(sh); 
How does setinterval work in js? How do you stop setinterval?

js Instance Code 1:

function auto(){ 
alert("到時間了") 
} 
var monitorInterval = null;  
function setAuto(time,isFrist){ 
var intervalTime=time; 
if(isFrist!="1"){ 
if(intervalTime!="off"){ 
monitorInterval= setInterval("auto()", intervalTime*1000); 
}else{ 
if(monitorInterval){    
clearInterval(monitorInterval); 
monitorInterval = null; 
} 
} 
} 
} 


html Instance Code 2:

<table> 
<tr> 
<td nowrap="nowrap" bgcolor="#E8E8E8">自動更新</td> 
<td align="left" bgcolor="#E8E8E8"><select 
onchange="setAuto(this.value,'0')"> 
<option value="10">10sec</option> 
<option value="20">20sec</option> 
<option value="30">30sec</option> 
<option value="60">1min</option> 
<option value="300">5min</option> 
<option value="600">10min</option> 
<option value="1800">30min</option> 
<option value="3600">60min</option> 
<option value="off">Stay</option> 
</select></td> 
</tr> 
</table> 

Use setinterval to synchronize the loading of more than one Store

We know that the Ext js load Store is asynchronously loaded, which has many benefits, which are not explained here. H owever, sometimes it also requires multiple store synchronous loading, such as dynamic parsing to generate a chart, you need to load the chart style, chart axis, chart series and chart data at the same time before the full analysis of the generated chart, any store is not loaded, the parsing data will cause parsing errors, so you must ensure that all store load is completed to correctly parse. H ow do I save synchronization for multiple store loads? This is achieved as follows:

var bChartArr =[false, false, false, false];  
//加载图表轴  
Ext.getStore("ChartAxes").load(  
{  
    params:{ queryId:queryId },  
    callback:function(){  
        bChartArr[0] = true;  
    }  
});  
//加载图表序列  
Ext.getStore("ChartSeries").load(  
{  
    params:{ queryId:queryId },  
    callback:function(){  
        bChartArr[1] = true;  
    }  
  
});  
//加载图表样式  
Ext.getStore("ChartStyle").load(  
{  
    params:{ queryId:queryId },  
    callback:function(){  
        bChartArr[2] = true;  
    }  
});  
// 按钮  
Ext.getStore("Buttons").load(  
{  
    params:{query_id:queryId},  
    scope:this,  
    callback:function(){  
        bChartArr[3] = true;  
    }  
});  
var me = this;  
// 等待所有的Storoe加载完成后执行  
var timer = setInterval(function(){  
    if(bChartArr[0] && bChartArr[1] && bChartArr[2] && bChartArr[3]){  
        clearInterval(timer); // 清除等待  
        // 解析图表样式、轴、序列动态生成图表  
        me.createChartPanel();  
    }  
},100);  
This effectively solves the synchronization problem of multiple asynchronously loaded storexes in Ext.


Description: An array is used here to determine if the data is loaded. In fact, two other methods should be 20:


How does setinterval work in js? How do you stop setinterval?

1, the use of a count instead of an array, each store load complete to add 1 to the count, and finally judge the count reached the expected value;

2, do not use callback for store, but use store's isLoading() method, when all Stroe's isLoading ( ) are returned to false think the load is complete.


What if there is interference between multiple settervals in the JS script?

It is certain that cannot be executed at the same time, there must be a sequence, but it can run almost simultaneously. If you are sure that it is a problem of interturbation, you can define only one setinterval, for example:

var timeIntervalNumber = 1;

var timeInterval = setInterval('doSomething()', 1000);

function doSomething() {

if (timeIntervalNumber % 2) {...}

if (timeIntervalNumber % 5) {...}

timeIntervalNumber ++;

if (timeIntervalNumber >= 2 * 5) {

timeIntervalNumber = 1;

}

}


Or, as shown in the following code, the page will not report an error or a case.
var firstInterval;
var secondInterval;
function firstAlert(){
	if(firstInterval) clearInterval(firstInterval);
<span style="white-space:pre">	</span>//处理所有
<span style="white-space:pre">	</span>.........
<span style="white-space:pre">	</span>firstInterval = setInterval('firstAlert()', 1000*2);
}


function secondAlert(){
	if(secondInterval) clearInterval(secondInterval);
<span style="white-space:pre">	</span>//处理所有
<span style="white-space:pre">	</span>.......


secondInterval = setInterval('secondAlert()', 1000*3);
	}