In this article, we are going to learn how to change the setInterval() time after running one element. The setInterval() method reads the timing once and invokes the function at regular intervals. There are two methods to solve this problem which are discussed below:
- Using clearInterval() method
- Using the setTimeout() method.
Method 1: Using clearInterval() method.
The setInterval() method returns a numeric ID. This ID can be passed to the clearInterval() method to clear/stop the setInterval timer. In this technique, we keep firing clearInterval() after each setInterval() to stop the previous setInterval() and initialize setInterval() with a new counter.
Syntax:
clearTimeout(name_of_setTimeout)
Example: This example shows the use of the above-explained approach.
html
<!DOCTYPE html> < html > < head > < title > How to Change the Time Interval of setinterval() Method after Running one Element using JavaScript ? </ title > </ head > < body > < div id = "message" ></ div > < script > // Output message let msg = document.getElementById("message"); let t = 200; // Timer // Stores the setInterval ID used by // clearInterval to stop the timer var interval; f1(); // Function that changes the timer function changeTimer() { t = t * 1.2; } // Function that run at irregular intervals function f1() { // Clears the previous setInterval timer clearInterval(interval); msg.innerHTML += "< br >Function Fired</ br >" changeTimer(); interval = setInterval(f1, t); } </ script > </ body > </ html > |
Output:
Method 2: Using the setTimeout() method.
This technique is easier and simpler than the previous one. The setTimout() method fires a function after a certain period. The timer is the time after which we want to run our function. In this technique, after performing the desired task, we change the value of the timer and call setTimeout() again. Now, since the value of the timer changes, each function call is invoked at different intervals.
Syntax:
window.setTimeout(function, milliseconds);
Example: This example shows the use of the above-explained approach.
html
<!DOCTYPE html> < html > < head > < title > How to Change the Time Interval of setinterval() Method after Running one Element using JavaScript ? </ title > </ head > < body > < div id = "message" ></ div > < script > // Output message var msg = document.getElementById("message"); var t = 200; // Timer // Stores the setInterval ID used by // clearInterval to stop the timer var interval; f1(); // Function that changes the timer function changeTimer() { t = t * 1.2; } // Function that run at irregular intervals function f1() { // Clears the previous setInterval timer clearInterval(interval); msg.innerHTML += "< br >Function Fired</ br >" changeTimer(); interval = setInterval(f1, t); } </ script > </ body > </ html > |
Output: