How can I use setInterval and clearInterval?
setInterval
sets up a recurring timer. It returns a handle that you can pass into clearInterval
to stop it from firing:
var handle = setInterval(drawAll, 20);
// When you want to cancel it:
clearInterval(handle);
handle = 0; // I just do this so I know I've cleared the interval
On browsers, the handle is guaranteed to be a number that isn't equal to 0
; therefore, 0
makes a handy flag value for "no timer set". (Other platforms may return other values; Node.js's timer functions return an object, for instance.)
To schedule a function to only fire once, use setTimeout
instead. It won't keep firing. (It also returns a handle you can use to cancel it via clearTimeout
before it fires that one time if appropriate.)
setTimeout(drawAll, 20);
How to use setInterval() and clearInterval() in the same function
You need to push the interval id in a global variable. Like that you can use another function to stop the interval when you want.
Like
let intervalId; // define `count` globaly
let timer = document.getElementById('timer')
const timerStop = () => {
clearInterval(intervalId)
}
const timerRestart = () => {
timerStop()
timer.innerHTML = 100;
}
const timerStart = () => {
timerStop(); // Stop timer by security, e.g. if you call `timerStart()` multiple times
intervalId = setInterval(() => {
let timeLeft = timer.innerHTML;
if (+timeLeft > 0) {
timer.innerHTML = +timeLeft - 1
} else {
timerRestart();
gameOverMessage()
}
}, 1000)
}
<div id="timer">100</div>
<div>
<button onclick="timerStart()">Start</button>
<button onclick="timerStop()">Pause</button>
<button onclick="timerRestart()">Restart</button>
</div>
node.js: how to use setInterval and clearInterval?
Using setInterval()
What if you need to repeat the execution of your code block at specified intervals? For this, Node has methods called setInterval() and clearInterval(). The setInterval() function is very much like setTimeout(), using the same parameters such as the callback function, delay, and any optional arguments for passing to the callback function.
A simple example of setInterval() appears below:
var interval = setInterval(function(str1, str2) {
console.log(str1 + " " + str2);
}, 1000, "Hello.", "How are you?");
clearInterval(interval);
This is another way when you want to keep only one interval running every minute
function intervalFunc() {
console.log("Hello!!!!");
}
setInterval(intervalFunc,1500);
In the above example, intervalFunc() will execute about every 1500 milliseconds, or 1.5 seconds, until it is stopped . Hope this helps.
Proper way to setInterval and clearInterval
The setInterval()
function returns an ID. This is what you want to assign to hmm
.
Also, the first parameter of setInterval()
is the function you want to call every interval.
var hmm = null;
function appendStuff(){
$("p").append("<b>Appended text</b>");
};
$("#start").click(function() {
console.log("startClicked"); // working...
hmm = window.setInterval(appendStuff, 1000) // working...
});
$("#stop").click(function() {
console.log("stopClicked"); // working...
window.clearInterval(hmm)
});
setInterval() and clearInterval() in React
Since launch
is just an ordinary variable, its value will not survive across rerenderings of TimerPanel
. You'll need to store it inside a ref with useRef
// add useRef to your imports from react
import { useRef } from "react";
function TimerPanel(props) {
const launch = useRef();
var secLeft =
parseInt(props.timerNow.min) * 60 + parseInt(props.timerNow.sec);
const startCountDown = () => {
props.setIsPaused(false);
clearInterval(launch.current) // clean up any old timers
launch.current = setInterval(decrement, 1000);
};
function decrement() {
if (secLeft > 0 && !props.isPaused) {
secLeft--;
var minCountDown = Math.floor(secLeft / 60);
var secCountDown = Math.floor((secLeft % 60) * 100) / 100;
props.setTimerNow({
...props.timerNow,
min: minCountDown,
sec: secCountDown,
});
}
}
const pauseCountDown = () => {
props.setIsPaused(true);
clearInterval(launch.current);
};
const reset = () => {
props.setIsPaused(false);
clearInterval(launch.current);
props.setSessionLength(props.initialTimer.min);
props.setTimerNow({
...props.timerNow,
min: props.initialTimer.min,
sec: props.initialTimer.sec,
});
};
// ...
}
Need help to use setInterval and clearInterval in Javascript
Generally:
- Use
setInterval
if you need a continuous call to a function. - Use
setTimeout
if you want to delay the calling of a function.
And in your case. You want change the picture with delay if selectCity
is changed. Therefore use setTimeout
instead.
Example:
let currentIndex = 0
selectCity.addEventListener('change', () => {
setTimeout(() => {
if (images.length < currentIndex) {
celeb.src = images[currentIndex]
currentIndex += 1
}
}, 7000)
})
Test
setTimeout
in your browser:
document.getElementsByTagName('button')[0].addEventListener('click', function() {
setTimeout(() => console.log('Clicked'), 5000)
})
<button>Console after 5 seconds</button>
how to clearInterval if any previous setInterval is running in REACT?
The interval
variable gets created each time the App
function is run.
Which is in this case each time you press Enter.
It can be fixed by placing it out of the App function.
let interval;
const App = () => {
const [ctime, setctime] = useState();
const enterdown = (value) => {
clearInterval(interval);
setctime(value);
interval = setInterval(() => {
value--;
if (value === 0) {
clearInterval(interval);
}
setctime(value);
}, 1000);
};
// ...
Another solution would be using useRef
How do I correctly use setInterval and clearInterval to switch between two different functions?
You need to capture the return value from setInterval( ... )
into a variable as that is the reference to the timer:
var interval;
var count = 0;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
/* ... code ... */
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count === 10)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
Related Topics
JavaScript Add Leading Zeroes to Date
How to Post a File from a Form With Axios
Synchronized Scrolling Using Jquery
Override Styles in a Shadow-Root Element
Setting Rounded Corners for Svg:Image
Can't Change Border Color of Material-Ui Outlinedinput
Scoping the Results for Rails3 Jquery Autocomplete Plugin
How to Use Jquery with Node.Js
Run Greasemonkey Script on the Same Page, Multiple Times
JavaScript: Difference Between .Foreach() and .Map()
Indexof Method in an Object Array
Iterating Over Result of Getelementsbyclassname Using Array.Foreach
Modify a CSS Rule Object with JavaScript
Toggle Visibility Property of Div
Refused to Load the Script Because It Violates the Following Content Security Policy Directive