I am trying to implement a stopwatch. When the start button is pressed setInterval is called. How can I stop by running clearInterval when the stop button is pressed, without having a global variable to pass as a parameter to clearInterval
<body>
<p class="clock">00:00:00</p>
<button class='start'>Start</button>
<button class="stop">Stop</button>
<script>
let totalMilliSeconds = 0;
function tick(){
totalMilliSeconds++;
let hours = Math.floor(totalMilliSeconds/3600)
let minutes = Math.floor(totalMilliSeconds/3600)
let seconds = Math.floor(totalMilliSeconds/360)
document.querySelector('.clock').textContent = `${hours}:${seconds}:${totalMilliSeconds}`
}
function start(){
return setInterval(tick,1)
}
document.querySelector('.start').addEventListener('click',start)
document.querySelector('.stop').addEventListener('click',start)
</script>
<p>
</body>
</html>
You're clearly going to need to store the reference to the interval somewhere. It's not clear what you mean by not having a global variable; one solution would be to declare it at the top:
let totalMilliSeconds = 0;
let interval = null;
function tick(){
totalMilliSeconds++;
let hours = Math.floor(totalMilliSeconds/3600)
let minutes = Math.floor(totalMilliSeconds/3600)
let seconds = Math.floor(totalMilliSeconds/360)
document.querySelector('.clock').textContent = `${hours}:${seconds}:${totalMilliSeconds}`
}
function start(){
if (!interval) interval = setInterval(tick,1);
return interval;
}
function stop() {
if (interval) clearInterval(interval);
interval = null;
}
document.querySelector('.start').addEventListener('click',start)
document.querySelector('.stop').addEventListener('click',stop)
Thanks to JS scopes, the variable interval will be available in all functions declared in the script.
You just need to use the Interval ID returned by setInterval(). In your case, you could do something like that:
let intervalId;
document.querySelector('.start').addEventListener(
'click',
() => {intervalId = start();}
);
Then you can do clearInterval(intervalId) whenever you want.
If you want to avoid global variables you can wrap the whole thing in function declaration, then call it immediately. Any variables declared with var or let will only exist within the function's scope.
Example using Christoph's code sample:
(function() {
let totalMilliSeconds = 0;
let interval = null;
function tick(){
totalMilliSeconds++;
let hours = Math.floor(totalMilliSeconds/3600)
let minutes = Math.floor(totalMilliSeconds/3600)
let seconds = Math.floor(totalMilliSeconds/360)
document.querySelector('.clock').textContent = `${hours}:${seconds}:${totalMilliSeconds}`
}
function start(){
if (!interval) interval = setInterval(tick,1);
return interval;
}
function stop() {
if (interval) clearInterval(interval);
interval = null;
}
document.querySelector('.start').addEventListener('click',start)
document.querySelector('.stop').addEventListener('click',stop)
})();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures
Related
How i can stop a function in another function?
For example:
var snow = function(){
var interval = setInterval( function(){
alert('letItSnow')
}, 1000);
};
snow();
clearInterval(snow.interval) - exception
In javascript, access scopes are limited via function declarations, so your locally declared variables won't be accessible outside, hence you must return it or set it to a global variable (variable available in parent scope)
you need to make a slight adjustment to your function, do it like this:
var snow = function(){
return setInterval(function(){
alert('letItSnow');
}, 1000);
};
var interval = snow();
//on some event -- clearInterval(interval)
you can also make the setTimeout and its returned id a property to the function which would be available on all of its instances i.e.
var snowClass = function(){
this.init = function(msg){
this.interval = setInterval(function(){alert(msg)},1000);
}
}
var snowObj = new snowClass();
snowObj.init('Let it snow');
//on some event -- clearInterval(snowObj.interval)
you referring to snow.interval which assumed to be property of snow object. but in your code interval is just local variable. instead you might want to define interval in the global scope so it will be accessible globally http://www.w3schools.com/js/js_scope.asp
var interval, snow = function(){
interval = setInterval( function(){
console.log('letItSnow')
}, 1000);
};
snow();
clearInterval(interval);
If I understand the question correctly, you want to stop the interval outside of the snow function.
You can declare the interval variable outside of the snow function in order to use it (to clear the interval) outside of the snow function.
var interval;
var snow = function(){
interval = setInterval(
function(){
alert('letItSnow')
},
1000
);
};
snow();
clearInterval(interval);
try this in your code
var timeout1 = {};
var timeout2 = {};
function function1(){
//codes
if(timeout2){
clearTimeout(timeout2);
}
timeout1 = setTimeout("function1()",5000);
}
function function2(){
//codes
if(timeout1){
clearTimeout(timeout1);
}
timeout2 = setTimeout("function2()",5000);
}
I have to find a button when it will appear. In order to do that I use setInterval. When it finds this button, it gives to my variable needed value. I check it inside the setTimeout, but after setTimeout(outside these method) my global variable became as before setTimeout. How to fix that?
let foundValue;
function findById(id) {
let interval = setInterval(() => {
if (document.getElementById(id)){
let foundValue = document.getElementById(id);
clearInterval(interval);
}
}, 1000);
return foundValue;
}
It's because you're re-declaring foundValue inside setInterval so you should remove the second let, for example:
let foundValue;
function findById(id) {
let interval = setInterval(() => {
if (document.getElementById(id)){
foundValue = document.getElementById(id);
clearInterval(interval);
}
}, 1000);
return foundValue;
}
I'm trying to stop/clear the interval but i'm getting an error.
code below:
function play(){
function sequencePlayMode() {
var arg1;//some arguments
var arg2;//some arguments
changeBG(arg1,arg2);//here is function that changes the background
}
var time = 5000;
var timer = setInterval(sequencePlayMode, time);//this starts the interval and animation
}
function stop(){
var stopPlay = clearInterval(sequencePlayMode);//here i'm getting error "sequencePlayMode is not defined"
}
$("#startAnimation").click(function(){
play();
});
$("#stopAnimation").click(function(){
stop();
});
Can someone help me with this please?
You need to use the variable that you store the function in and not the function that you call it. You also need to make the variable accessible to the other function.
(function () {
var timer; //define timer outside of function so play and stop can both use it
function play(){
function sequencePlayMode() {
var arg1;//some arguments
var arg2;//some arguments
changeBG(arg1,arg2);//here is function that changes the background
}
var time = 5000;
timer = setInterval(sequencePlayMode, time);//this starts the interval and animation
}
function stop(){
var stopPlay = clearInterval(timer);
}
$("#startAnimation").click(function(){
play();
});
$("#stopAnimation").click(function(){
stop();
});
})();
Here i attached my code. am clear the time out function when dialog is open.but its not working properly.When i open my dialog the count down decreasing from 20 but in between 20 seconds if i close and open the dialog , the timing is collapsing each other.
function(){
var time =20;
flag = false;
clearTimeout(startTimer);
startTimer = function(){
if(!flag){
var finTime = time - 1;
time = finTime;
setTimeout(startTimer,1000);
if(time==0){
flag = true; }
$("#input").text(time);
} else {
clearTimeout(startTimer,1000);
}
};
setTimeout(startTimer,1000);
};
I have tried this code also
dialogOpen = function(){
$("#dialog").dialog('open');
startTimer();
stopTimer();
}
startTimer = function() {
time = 20;
flag = false;
setTimeout(startTime, 1000);
};
stopTimer = function() {
flag = true;
time = 0;
clearTimeout(startTime);
};
startTime = function(){
if(!flag){
var finTime = time - 1;
time = finTime;
setTimeout(startTime,1000);
if(time==0){
flag = true;
}
$("#input").text(time);
} else {
clearTimeout(Time);
}
};
You have to assign setTimeout to a variable
var timer;
timer = setTimeout(startTimer,1000);
and you can clear the setTimeout using clearTimeout by passing the variable.
clearTimeout(timer);
To call clearTimeout() you want to pass in the intervalVariable that was returned by setTimeout(), not the function, so it would look like:
var intervalVariable = setTimeout(startTimer,1000);
clearTimeout(intervalVariable);
It's best to thing of intervalVariable as the ID for the timeout that is then used by the browser to cancel it.
Set a global variable before your startTimer function, then set it to the return of setTimeout() and use it in place of startTimer in clearTimeout().
Right now i have this 1 minute timer in my background page that runs forever i would like to be able to start and stop it from an options page.
chrome.browserAction.setBadgeBackgroundColor({color:[0, 0, 0, 255]});
var i = 1;
window.setInterval(function(timer) {
chrome.browserAction.setBadgeText({text:String(i)});
i++;
}, 60000);
setInterval() method of the Window object schedules a function to be invoked repeatedly at intervals of the specified number of milliseconds. setInterval() returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function. Read more about How Javascript Timers work. With that you can write something like this:
My.Controller = {};
(function() {
var interval = 10;
var timer = null;
function init (param) {
// initialisations if any
}
// Override the default interval of 10 seconds by passing new interval
function startAction (param, tInterval) {
// Set a timer
var ti = (!tInterval) ? interval : tInterval;
timer = setInterval(My.Controller.action, ti * 2000);
}
function action () {
// Logic here
}
function stopAction () { clearInterval(timer); }
var c = My.Controller;
c.init = init;
c.startAction = startAction;
c.stopAction = stopAction;
})(); // end Controller
Now you can say My.Controller.startAction() to start the timer and and My.Controller.stopAction() to stop.
Read and explore about namespaces in JavaScript.
Hope this helps.