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();
Related
So, imagine the following code below:
setInterval(() => {
var thisInterval = this;
fn1();
fn2();
if(someMouseDownEventDeclaredSomewhereElse){
clearInterval(thisInterval);
}
},100);
Is this the correct method for getting the current interval? Say I wanna do so without setting a variable to this loop because I want it to be an unnamed and non-stored interval. In simpler words: Is there a way to get an unnamed interval from within, like with this or something?
You can do something like this;
function f() {
fn1();
fn2();
if(!someMouseDownEventDeclaredSomewhereElse){
setTimeout(f, 100);
}
}
setTimeout(f, 100);
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)
I have the following issue. While the timer_mou starts counting, when the pause equals closeit it does not clear the interval.
What am I missing here?
function my_timer(pause){
console.log('function: '+pause);
var timer_mou = setInterval(function() {
console.log('counting');
}, 5000);
if (pause == 'closeit') {
clearInterval(timer_mou);
}
}
Just put the setInterval out of the pause function to define the variable timer_mou in the global scope, then when you call your function it will clear it correctly, instead of defining it on every call of the function, check the working example below.
Hope this helps.
var i = 0;
var timer;
start();
$('#pause').on('click',function(){
pause()
})
$('#restart').on('click',function(){
restart()
})
function pause(){
clearInterval(timer);
}
function restart(){
i=0;
pause()
start();
}
function start(){
timer = setInterval(function() {
i++;
console.log('Counting '+i);
},1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='pause'>Pause</button>
<button id='restart'>Restart</button>
You need to define timer_mou outside of the function. In your case you won't be able to clear the timer as you have lost reference to the timer and you create a new timer instance with every function call.
Try something like:
var timer_mou;
function start_timer() {
timer_mou = setInterval(function() {
console.log('counting');
}, 5000);
}
function stop_timer() {
clearInterval(timer_mou);
}
This is a very annoying problem that has to do with scope. When you declare the setInterval inside of your function, the only place you can clear it is inside of that iteration of the function. So,
my_timer("") //Starts a timer in the function
my_timer("closeit") //Starts a timer in the function, then stops it
//with the other timer running in the background
You can reduce the problem to the fact that your interval gets declared multiple times, and you can only stop it inside of the function. So, if you want the my_timer function to start the timer, but stop if you give it the parameter of "pauseit", you could implement something like this:
function my_timer(pause){
console.log('function: '+pause);
if(typeof timer_mou === "undefined"){ //If the interval already exists, don't start a new one
timer_mou = //Defines in global scope
setInterval(function() {
console.log('counting');
}, 5000);
}
if (pause == 'closeit') {
clearInterval(timer_mou);
}
}
So, in the new version of your function, it checks if the interval is defined, and if not, defines it in the global scope so you can remove it later.
Done on mobile, so that's my excuse for bad formatting and spelling errors.
Preety straight forward question, though I can't find the answer anywhere
I tried these two ways:
setInterval(function(){object/*or this*/.method()},500)
and
setInterval('object/*or this*/.method()',500)
setInterval in fact expects a method as the first argument, though there is an alternative syntax where the first argument can be a string of code (not recommended by most)
If you're having issues with that code, it may have to do with the scope of 'this'
setInterval(function(){this.method()},500)
In the above code, 'this' will refer to the closure itself, and wouldn't be the same as 'this.method' occurring outside of that closure. For example, the following would work:
function MyClass() {
this.thingy = 'yep this is a thingy'
}
var myClass = new MyClass()
// Will log 'MyClass yep this is a thingy'
setInterval(function() { console.log('MyClass', myClass.thingy) }, 1000)
Whereas the following will not work (presuming instantiating the object and calling foo()):
function MyOtherClass() {
this.thingy = 'also a thingy'
}
// Will log 'MyOtherClass undefined'
MyOtherClass.prototype.foo = function() {
setInterval(function() { console.log('MyOtherClass', this.thingy) }, 1000)
}
The second example will work if we get around using 'this' within the closure (presuming instantiating the object and calling bar()):
MyOtherClass.prototype.bar = function() {
var that = this
setInterval(function() { console.log('MyOtherClass', that.thingy) }, 1000)
}
Also be sure that setInterval is being passed the name of a function:
setInterval(someFunction, 500)
rather than executing a function as an argument
setInterval(someFunction(), 500)
This last line of code is usually a mistake, unless someFunction() returns a function itself ;)
The difference between your 2 ways for passing a function to setInterval is whether you want to pass your function as refrence of just copy of it. Allow me to explain it by example:
-1 Referring(demo):
var obj = {
testMethod: function () {
console.log('function (testMethod): intial output');
}
}
setInterval(function () {
obj.testMethod()
}, 1000);
obj.testMethod = function () {
console.log('function (testMethod): changed output');
}
when you run this code, the result 'll be execution of the modified version of testMethod. Because here you dont copy the function! Instead, you refer to it. So whenever function implementation is changed, the last modified version is executed.
-2 Copying(demo):
var obj = {
testMethod: function () {
console.log('function (testMethod): intial output');
}
}
setInterval(obj.testMethod, 1000);
obj.testMethod = function () {
console.log('function (testMethod): changed output');
}
Here all you do is you are passing a copy of the last defined version of the function testMethod to setInterval. So whatever changes you do to testMethod, the result of setInterval will not be changed.
I have this function.
function changeFrame(){
var time = setInterval(start, 250);
}
and I want to stop it from firing in another function, but haven't been able to figure out how to do it.
Do you mean this?
function changeFrame(){
var time = setInterval(function() {
// Do stuff
}, 250);
}
Think it's in the comments.
Ok amended the fiddle to do what you want. I made time a global var. Call clearInterval in stop with the global var http://jsfiddle.net/QNWF4/3/
In order to call clearInterval you need to have the handle returned by setInterval. That means something will either be global to the page or global to a containing function in which your script resides.
function Timer()
{
var handle = null;
this.start = function (fn,interval) {
handle = setInterval(fn,interval);
};
this.stop = function ()
{
if (handle) { clearInterval(handle); handle = null; }
};
return this;
}