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);
}
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:
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)
This question already has answers here:
How to access the correct `this` inside a callback
(13 answers)
'this' in function inside prototype function [duplicate]
(8 answers)
Closed 4 years ago.
How do I make my objects property available within the callback?
//entrypoint.js
var DeviceManager = require('./class')
DM = new DeviceManager()
DM.start();
var t = setInterval(function() {
console.log("Module.isLoaded = " + DM.isLoaded);
}, 500);
setTimeout(function() {
console.log("Stopping");
clearInterval(t);
DM.stop();
}, 10000);
//class.js
module.exports = class DeviceManager {
constructor(){
this.isLoaded = false;
this._timer= null;
}
start(){
console.log('starting timer')
this._timer = setInterval( function() {
console.log('timer callback')
this.isLoaded = !this.isLoaded;
},1000)
}
stop() {
console.log('stopping timer')
clearInterval(this._timer)
}
}
Basically this line doesnt work, because it doesnt have access to the correct this I assume.
this.isLoaded = !this.isLoaded
Also, since im all around pretty new at this, any feedback/corrections are very welcome.
Try using an arrow function for your setInterval while it's in the class.
An arrow function expression has a shorter syntax than a function expression and does not have its own this
start() {
this._timer = setInterval( () => {
this.isLoaded = !this.isLoaded;
}, 1000)
}
I am having a hard time getting a countdown timer working as I don't know what I am doing wrong. I am trying to setup a countdown timer using jQuery in a prototype.
The main problem I see so far is at the setInterval:
_self.counter = setInterval(_self.runTimer(_self),1000);
When I don't pass in the "this" I get NaN but when I do the countdown only happens once and then stops.
Here is my JSFiddle work so far:
http://jsfiddle.net/f9GN7/
Thank you in advance.
I've modified a little of your code, I changed setInterval to setTimeout.
var timer_code = function(){
this.counter;
this.timeCountDown = 30;
}
timer_code.prototype = {
init : function(){
var _self = this;
$('#start').on('click',function(e){
_self.setTimer();
});
},
setTimer : function(){
var _self = this;
// _self.counter = setInterval(_self.runTimer(_self),1000);
var timerLoop = function(){
if(_self.timeCountDown > 0){
_self.runTimer();
setTimeout(timerLoop, 1000);
}
};
timerLoop();
},
runTimer : function(){
var _self = this;
_self.timeCountDown--;
if(_self.timeCountDown <= 0){
// clearInterval(_self.counter);
$('#timer').html("DONE");
return;
}
$('#timer').html(_self.timeCountDown);
console.log(_self.timeCountDown);
}
}
var timer = new timer_code();
timer.init();
http://jsfiddle.net/f9GN7/1/
setInterval gets a function reference as its first parameter ..
This function may not return a function object, the function call you just passed needs to be called in the scoope of a closure
Keeping your code with just a few modifications :
setTimer: function(){
if(this.counter)
clearInterval(this.counter); // timer may have already been launched, it may need to be cleared if its value is an integer and is != 0
this.counter = setInterval(
(function (ref) {
return function () {
ref.runTimer();
}
})(this),
1000);
}
See Fiddle Here
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 8 years ago.
Below is my javascript code:
function showBranch_init() {
var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
for(a=0;a<id_arr.length;a++){
timeoutID = window.setTimeout(function() {
showBranch(id_arr[a]); // <-- Right here
}, 500);
}
}
How can I pass the value of id_arr[a] to showBranch funcion?
Currently the above code returns null for id_arr[a]
by introducing a new scope (by a function call) for each iteration step you can pass the argument like this:
function showBranch_init() {
var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
for(a=0;a<id_arr.length;a++){
(function(i) {
timeoutID = window.setTimeout(function() {
showBranch(id_arr[i]); // <-- Right here
}, 500*i);
})(a);
}
}
Updated to fullfill the 2nd req: showBranch() in 500ms steps..
http://jsfiddle.net/HXc4d/
function showBranch_init() {
var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
for(a=0;a<id_arr.length;a++){
timeoutID = window.setTimeout(function(idvalue) {
showBranch(idvalue);
}(id_arr[a]), 500);
}
}
EDIT: The problem with your solution is the fact that when the code executes (timeout) id_arr no longer exists in the executing scope, thus leading to undefined result. When sending the variable as an argument it "stays" with the funciton itself, regardless of the executing scope.
function showBranch_init() {
var id_arr = ["jdc_b1","jdc_b2","jdc_b3","jdc_b4"];
timeoutID = window.setTimeout(function() {
for(a=0;a<id_arr.length;a++){
showBranch(id_arr[a]); // <-- Right here
}
}, 500);
}
can you do that?? O_O