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(); … Read more

Making a live clock in javascript

Add a span element and update its text content. var span = document.getElementById(‘span’); function time() { var d = new Date(); var s = d.getSeconds(); var m = d.getMinutes(); var h = d.getHours(); span.textContent = (“0” + h).substr(-2) + “:” + (“0” + m).substr(-2) + “:” + (“0″ + s).substr(-2); } setInterval(time, 1000); <span id=”span”></span> … Read more

recursive function vs setInterval vs setTimeout javascript

Be carefull.. your first code would block JavaScript event loop. Basically in JS is something like list of functions which should be processed. When you call setTimeout, setInterval or process.nextTick you will add given function to this list and when the right times comes, it will be processed.. Your code in the first case would … Read more

Javascript setInterval not working

A lot of other answers are focusing on a pattern that does work, but their explanations aren’t really very thorough as to why your current code doesn’t work. Your code, for reference: function funcName() { alert(“test”); } var func = funcName(); var run = setInterval(“func”,10000) Let’s break this up into chunks. Your function funcName is … Read more

How to setInterval for every 5 second render with React hook useEffect in React Native app?

You need to clear your interval, useEffect(() => { const intervalId = setInterval(() => { //assign interval to a variable to clear it. setState(state => ({ data: state.data, error: false, loading: true })) fetch(url) .then(data => data.json()) .then(obj => Object.keys(obj).map(key => { let newData = obj[key] newData.key = key return newData }) ) .then(newData => … Read more

How to clearInterval with unknown ID?

From quick test, all major browsers (latest Chrome, Firefox and IE) give pretty small numbers as the ID so just looping “blindly” over all possible numbers should work just fine: function ClearAllIntervals() { for (var i = 1; i < 99999; i++) window.clearInterval(i); } Full example: window.onload = function() { window.setInterval(function() { document.getElementById(“Tick”).innerHTML += “tick<br … Read more