How to use setinterval in js? How can setinterval stop?

setinterval() is a function called regularly, which can call functions or calculate expressions according to the specified period (in milliseconds).

The function of setinterval() is to call the function, method or object at regular intervals while playing the animation.

The setInterval() method will keep calling the function until clearInterval() is called or the window is closed.

The 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 parameters code is your js code, and millisec is the time interval in milliseconds.

The first format is the default syntax for the setInterval function in the standard actions panel, and the second format is the method used in expert mode actions.

The parameter function is a function name or a reference to an anonymous function.

The object parameter specifies an object derived from the Object object.

methodName specifies the method to call in the object parameter.

interval specifies the time between two calls to function or methodName, in milliseconds.

The following arg1 and so on are optional parameters, which are used to formulate the parameters passed to function or methodName.

setInterval The time interval it sets is less than the animation frame rate (such as 10 frames per second, which is equivalent to 100 milliseconds), and the function is called at a time interval as close as possible to the interval. And the updateAfterEvent action must be used to ensure that the screen is refreshed frequently enough. If the interval is greater than the animation frame rate, it is only called every time the playhead enters a certain frame to reduce the impact of refreshing the screen each time.

The following example calls an anonymous function every 1 second.

setInterval(function(){trace(“I will display it every 1 second”)}, 1000);//The function(){} here is a function without a function name. Become an anonymous function, the following 1000 is the time interval, the unit is milliseconds.

function show1(){
    trace("Display every 1 second");
}
function show2(str){
    trace(str);
}
setInterval(show1,1000);
setInterval(show2,2000,"I will show it every 2 seconds");

The setInterval method of the function has been introduced above. Next we will introduce the object’s setInterval method.

First, write an example of setInterval calling an object’s method in an action, which does not need to pass parameters.

myobj=new Object();//Create a new object
myobj.interval=function){
    trace("Display every 1 second");
}//Method to create an object.
setInterval(myobj,"interval",1000);//Set the time interval to call the method of the object.

Next, we will introduce how to pass parameters. In fact, the reason is the same as the passing parameters of the function.

myobj=new Object();
myobj.interval-function(str){
    trace(str);
}
setInterval(myobj,"interval",2000,"I will display it every 2 seconds");

Notice. To call a method defined for an object, you must use the second syntax form in expert mode. In this case, let’s make a picture that dynamically displays the time. This can be achieved 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;
}//The datetime here is the variable name of a dynamic text box.

Use the clearinterval command to stop setinterval

Intervals can be created with the setInterval command and terminated with the clearInterval command. The parameters used by setInterval have two formats. In the first form, the parameters you pass to setInterval can be a function name, an interval over time, and some related parameters passed to the previous function. When setInterval runs it will sequentially pass the listed parameters to the specified function at specified intervals until you call clearInterval to terminate it. The relevant sample code is as follows:

function show(){
    trace("I will display it every second");
}
var sh;
sh=setInterval(show,1000);
clearInterval(sh);

js example code 1:

function auto(){
    alert("It's time")
}
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 example code 2:

<table>
    <tr>
        <td nowrap="nowrap" bgcolor="#E8E8E8">Auto Update</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 load multiple Ext Stores synchronously

We know that Ext js loads the Store asynchronously, which has many benefits, which will not be explained here. However, sometimes multiple stores need to be loaded synchronously. For example, for dynamic parsing to generate charts, the chart style, chart axis, chart sequence, and chart data must be loaded at the same time before the chart can be completely parsed and generated. When any store is not loaded, the parsed data will be displayed. Causes parsing errors, so you must ensure that all stores are loaded before parsing can be done correctly. How to save the synchronization of multiple store loading? The specific implementation is as follows:

var bChartArr =[false, false, false, false];
//load the chart axes
Ext.getStore("ChartAxes").load({
    params: { queryId: queryId },
    callback: function () {
        bChartArr[0] = true;
    }
});
//load chart sequence
Ext.getStore("ChartSeries").load({
    params: { queryId: queryId },
    callback: function () {
        bChartArr[1] = true;
    }
  
});
//load chart style
Ext.getStore("ChartStyle").load({
    params: { queryId: queryId },
    callback: function () {
        bChartArr[2] = true;
    }
});
// button
Ext. getStore("Buttons"). load({
    params:{query_id:queryId},
    scope:this,
    callback: function () {
        bChartArr[3] = true;
    }
});
var me = this;
// Wait for all Storoe to be loaded and execute
var timer = setInterval(function(){
    if(bChartArr[0] & amp; & amp; bChartArr[1] & amp; & amp; bChartArr[2] & amp; & amp; bChartArr[3]){
        clearInterval(timer); // clear wait
        // Parse the chart style, axis, and sequence to dynamically generate the chart
        me. createChartPanel();
    }
},100);

This effectively solves the synchronization problem of multiple asynchronously loaded stores in Ext.

Description: An array is used here to determine whether the data has been loaded. In fact, two other methods should also be possible:

1. Use a count instead of an array, add 1 to the count when each store is loaded, and finally judge that the count reaches the expected value;

2. Do not use callback for Store, but use store’s isLoading() method. When all Stroe’s isLoading() returns false, the loading is considered complete.

In the JS script, what should I do if there is interference between multiple setintervals?

It is certain that they cannot be executed at the same time, and there must be a sequence, but they can be executed almost at the same time. If you are sure that it is a problem of mutual interference, you can only define a 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 get stuck.

var firstInterval;
var secondInterval;
function firstAlert(){
if(firstInterval) clearInterval(firstInterval);
<span style="white-space:pre"> </span>//Process all
<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>//Process all
<span style="white-space:pre"> </span>.?…


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