This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 4 years ago.
documentation states that clearInterval() is required to be passed in a setIntervalId, therefore the function has to look like:
var logMe = setInterval(function () {...}, interval)
Above function is also being self-invoked as soon as the page loads.
If i try to put it in an anonymous function as below:
var logMe = function (interval) {
setInterval(function () {
console.log("whatever");
}, interval);
};
I can pass an interval argument, but I cannot stop it with:
function stopLogMe() {
window.clearInterval(logMe);
};
So the question is, can I create a function "setInterval" that I can pass an argument (interval) and also stop it using clearInterval ?
Define variable and assign timer to it when you're calling logMe function:
var interval = 2000;
var timer = null;
function logMe() {
timer = setInterval(function() {
console.log('hello!');
}, interval);
}
function stopLogMe() {
window.clearInterval(timer);
}
<button onclick="logMe();">Start</button>
<button onclick="stopLogMe();">Stop</button>
You need to somehow encapsulate the ID and the stop function inside a object or function. The ID must be in local context of the logger so it can access it when it needs to stop. It also allows you to create more then just one logger without making things to complex.
const Interval = function (fn, interval) {
this.id = setInterval(fn, interval)
this.clear= function () {
clearInterval(this.id)
}
}
// Create new logger
const myLogger = new Interval(function () {
console.log('Log me')
}, 1000)
// Clear interval after 5 seconds.
setTimeout(myLogger.clear.bind(myLogger), 5000)
Related
This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 3 years ago.
I have a global variable called interval, and I need to change this global variable to 5000 inside a function, so after waiting for 1 second, the setInterval function will now wait for 5 seconds. However, when I tried the code below, it only waits 1 second every time it's executed.
var timeToWait1 = 1000;
var timeToWait2 = 5000;
var interval = timeToWait1;
setInterval(function(){ waitFunction () }, interval);
function waitFunction() {
interval = timeToWait2;
} //end of function waitFunction()
Interval is set once and can't be changed, You'd need timeout.
var timeToWait1 = 1000;
var timeToWait2 = 5000;
setTimeout(waitFunction, timeToWait1);
function waitFunction() {
console.log('waitFunction called');
setTimeout(waitFunction, timeToWait2);
}
Once an interval has started, you can't change the duration it uses. You'll have to stop the interval and re-start it with the new duration.
let intervalId;
let makeInterval = duration => {
console.log('making a new interval');
intervalId = setInterval(waitFunction, duration);
};
makeInterval(1000);
function waitFunction() {
clearInterval(intervalId);
console.log('waitFunction running');
makeInterval(5000);
}
You might consider using a recursive setTimeout instead, to avoid the need for clearing:
let makeTimeout = duration => {
console.log('making a new timeout');
setTimeout(waitFunction, duration);
};
makeTimeout(1000);
function waitFunction() {
console.log('waitFunction running');
makeTimeout(5000);
}
This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 6 years ago.
Why is clearInterval() not working? what am I doing wrong? I tried a bunch of things but they don't seem to work out...
var s = 60;
var timer = null;
function Ftimer (){
document.getElementById("sec").innerHTML = s--;
}
document.getElementById("start").onclick = function () {
var timer = setInterval(function(){ Ftimer() }, 1000);
}
document.getElementById("stop").onclick = function () {
clearInterval(timer);
}
var timer makes the scope to the onclick function, not the global variable.
timer = setInterval(Ftimer, 1000);
This is due to you overwriting your initial timer variable here:
document.getElementById("start").onclick = function () {
// this clobbers your previous `timer` assignment
var timer = setInterval(function(){ Ftimer() }, 1000);
}
So fix it by simply removing the var and use the outer scoped timer variable:
document.getElementById("start").onclick = function () {
// this assigns to your previous `timer`
timer = setInterval(function(){ Ftimer() }, 1000);
}
I'm assigning to a variable, a function that uses setInterval, but I don't want the function to run until I call it. However, the function is running from just the assignment statement.
sessionClock = setInterval(function() {
console.log("Hi")
}, 1000)
I have also tried like this:
sayHi = function() {
console.log("Hi");
}
var sayHiStarter = setInterval(sayHi, 1000);
Both of these initiate the function and will log "Hi" to the console.
Why is it running on assignment? And what can do I do fix this?
If you only want to bind a function to setInterval, but call it later, you can use bind:
var sessionClock = setInterval.bind(null, function() {
console.log("Hi")
}, 1000);
//... later
var myInterval = sessionClock(); // start the timer
// ... later if you need to clear it
clearInterval(myInterval);
In principle, bind returns a new function that calls your original function (in this case, setInterval) with predefined arguments. So when you call sessionClock, that returned function is called. There a other aspects to bind, but they don't seem to apply in this context.
The call to setInterval does not return a function, but an identification for the created interval. This id is used to remove the interval when you don't want it to execute anymore:
sessionClock = setInterval(function() {
console.log("Hi")
}, 1000)
...
clearInterval(sessionclock);
What you want is something like this:
sessionClock = function () {
return setInterval(function() {
console.log("Hi")
},
1000);
}
//When needed
var intervalId=sessionClock();
jQuery (fragmented for simplicity)
The interval property contains an setInterval() function with in the object literal slider, the setInterval() defined in interval is invoking itself, or at-least appears to be, but why?
var slider = {
config : function(imgs, callback){
//mandatory
var images = $(imgs);
//optional
var animationInterval;
var animationTime;
callback(images);
},
target : 0,
get lastElem(){
return this.images.length-1;
},
interval : setInterval(function () {
setSlider();
}, 3000)
};
slider.config('ul.images li', setConfig);
slider.images.hide().first().show();
function setConfig(imgs){
slider.images = imgs;
}
function setSlider(dest) {
slider.target === slider.lastElem ? slider.target = 0 : slider.target++;
slider.images.hide().eq(slider.target).fadeIn(1000);
slider.triggers.removeClass('active').eq(slider.target).addClass('active');
}
JSFiddle
When you make an object literal, the values you type in are evaluated as expressions.
function square(x) {
return x * x;
}
var lookup = {
'two': square(2)
};
console.log(lookup['two']); // 4
Here, you're calling setInterval instead of square. setInterval takes a function and period and schedules that function to run repeatedly. It returns a numeric identifier of the scheduling, so that you can stop it later with clearInterval. For example, you could later do clearInterval(slider.interval); to stop setSlider from being called.
In your current code you are assigning the RESULT of setInterval() to the interval property. What I would suggest is to wrap the setInterval() call in a function, like this:
interval : function() {
setInterval(function() {
setSlider();
}, 3000);
}
Then, you should be able to call slider.interval()
This question already has answers here:
How can I pass a parameter to a setTimeout() callback?
(29 answers)
Closed 12 months ago.
function f1()
{
c = setTimeout(f2,200);
}
function f2()
{
//code
}
The above code is just fine. But what I want to ask that: can I use some argument in function f2() which is passed from the calling environment? That is:
function f1(v1)
{
c = setTimeout(f2(v1),200);
}
function f2(v2)
{
//code
}
Is it valid? Because I tried something like this,but the problem is that I am not able to clearTimeout by using variable c. I am not sure what to do.
Use Closure -
function f1(v1)
{
c = setTimeout(f2(v1), 200);
}
function f2(v2)
{
return function () {
// use v2 here, and put the rest of your
// callback code here.
}
}
This way you will be able to pass as many arguments as you want.
Since you are declaring c as a global variable (which is bad), you can easily clear the timeout using -
clearTimeout(c);
If you are still not being able to clear the timeout, it only means that the duration has elapsed and your callback fired, or there is some error somewhere else. In that case, post your code that you are using to clear your timeout.
You can either use the function.bind method or you can simply wrap the invocation
function f1(v1) {
c = setTimeout(function() {
f2(v1);
}, 200);
}
var timeout;
// Call `f2` with all arguments that was passed to the `f1`
function f1 () {
var args = arguments;
timeout = setTimeout(function () { f2.apply(this, args) }, 200);
}
Or in this way:
// Call `f2` with some params from `f1`
function f1 (v1) {
timeout = setTimeout(function () { f2(v1) }, 200);
}
Answer to your question: you couldn't clear the timeout because you execute function immediately.