Can't use clearInterval() method - javascript

It probably has to do with the 'timer' scope, but I can't get where is the problem. If anyone knows :)
function startTimer() {
let time = 0;
progress.style.width = time + '%';
let timer = function() {
setInterval(function() {
time += 0.5;
progress.style.width = time + '%';
if (time >= 100) {
clearInterval(timer);
}
}, 100);
}
timer();
}

You need to store the instance of setInterval() in order to clear it. You are passing a function into clearInterval()
function startTimer() {
let time = 0;
progress.style.width = time + '%';
// declare instance variable
let intervalTimer;
let timer = function() {
// assign instance
intervalTimer = setInterval(function() {
time += 0.5;
progress.style.width = time + '%';
if (time >= 100) {
// clear instance
clearInterval( intervalTimer);
}
}, 100);
}
timer();
}

const delay = 300 // time in ms
const intervalId = window.setInterval(()=>{ // do stuff here }, delay)
later
window.clearInterval(intervalId)

Related

How to stop and reset my countdown timer?

I'm trying to make my countdown timer do the following 4 things
When 'start' is clicked, change button to 'stop'
When 'stop' is clicked, stop the timer
When timer is stopped, show 'start' button
When 'reset' is clicked, reset the timer
$(document).ready(function() {
var counter = 0;
var timeleft = 5;
function nf(num) {
var s = '0' + num;
return s.slice(-2);
}
function convertSeconds(s) {
var min = Math.floor(s / 60);
var sec = s % 60;
return nf(min, 2) + ' ' + nf(sec, 2);
}
function setup() {
var timer = document.getElementById("timer");
timer.innerHTML = (convertSeconds(timeleft - counter));
var interval = setInterval(timeIt, 1000);
function timeIt() {
counter++;
timer.innerHTML = (convertSeconds(timeleft - counter));
if (counter == timeleft) {
clearInterval(interval);
}
}
}
$("#timer-button").click(function() {
setup();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I recently needed something like this too. I ended up writing an ES6 class for that.
In my solution, I used Events to notify other components about the timer. Here is a fiddle in which I met your needs, but I left my EventManager() calls to show what I actually did.
The used EventManager is this one. The timer counts in 100ms steps by default, but you can adjust this by calling startTimer() with the interval of choice.
class Timer {
constructor(maxTime, startValue = 0) {
// Actual timer value 1/10s (100ms)
this.value = startValue;
// Maximum time of the timer in s
this.maxTime = maxTime * 10;
this.timerRunning = false;
}
/**
* Starts the timer. Increments the timer value every 100ms.
* #param {number} interval in ms
*/
startTimer(interval = 100) {
if (!this.timerRunning) {
let parent = this;
this.timerPointer = setInterval(function() {
if (parent.value < parent.maxTime) {
parent.value++;
//EventManager.fire('timerUpdated');
$("span").text(parent.value / 10 + "/" + parent.maxTime / 10);
} else {
parent.stopTimer();
//EventManager.fire('timeExceeded');
$("button").text("Start");
this.resetTimer();
$("span").text("Countdown over");
}
}, interval);
this.timerRunning = true;
}
}
// Stops the Timer.
stopTimer() {
clearInterval(this.timerPointer);
this.timerRunning = false;
}
// Resets the timer and stops it.
resetTimer() {
this.stopTimer();
this.value = 0;
$("span").text("0/" + this.maxTime/10);
//EventManager.fire('timerUpdated');
}
// Resets the timer and starts from the beginning.
restartTimer() {
this.resetTimer();
this.startTimer();
}
}
let timer = new Timer(6);
$("#start-stop").click(function() {
if (timer.timerRunning) {
timer.stopTimer();
$("#start-stop").text("Start");
} else {
timer.startTimer();
$("#start-stop").text("Stop");
}
});
$("#reset").click(function() {
timer.resetTimer();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start-stop">
Start
</button>
<button id="reset">
Reset
</button>
<span>Timer: </span>
const div = document.querySelector('div');
const btn = document.querySelector('#timerBtn');
const resetbtn = document.querySelector('#reset');
let startFlag = 0;
let count = 0;
let intervalId;
const ms = 1000;
div.textContent = count;
btn.addEventListener('click', function() {
startFlag = startFlag + 1;
if(startFlag%2 !== 0) { // Start button clicked;
btn.textContent = 'Stop';
startTimer();
} else {
btn.textContent = 'Start';
stopTimer();
}
});
resetbtn.addEventListener('click', function() {
count = 0;
div.textContent = count;
});
function startTimer() {
intervalId = setInterval(() => {
count = count + 1;
div.textContent = count;
}, 1000);
}
function stopTimer() {
clearInterval(intervalId);
}
<div></div>
<button id="timerBtn">Start</button>
<button id="reset">Reset</button>

In Javascript, I'm using clearInterval() in a function/reset button - the timer resets, but keeps going

I've made a timer with setInterval():
var seconds = 0, minutes = 0;
var timer = document.querySelector("#timer");
var interval = null;
function beginTimer() {
var interval = setInterval(function(){
timer.innerHTML = minutes + " Minute(s) " + seconds + " Seconds";
seconds++;
if(seconds == 60) {
minutes++;
seconds = 0;
}
else if(minutes == 60) {
return "Out of time!";
}
}, 1000);
}
I've set a button in HTML to reset it, but when I use it to clear the timer, it continues running. This is the function with the clearInterval() in it.
function beginGame() {
cards = shuffle(cards);
for (var n = 0; n < cards.length; n++) {
allCards.innerHTML = "";
[].forEach.call(cards, function(item) {
allCards.appendChild(item);
});
cards[n].classList.remove("match", "open", "disable", "show");
}
//resetting values
moves = 0;
counter.innerHTML = moves;
star1.style.visibility = "visible";
star2.style.visibility = "visible";
star3.style.visibility = "visible";
lemon.style.visibility = "hidden";
seconds = 0;
minutes = 0;
clearInterval(interval);
var timer = document.querySelector("#timer");
timer.innerHTML = "0 Minute(s) 0 Seconds";
}
I've been researching this for a couple of days with no luck... could someone kindly help me understand how to stop the timer from continuing to run after reset is initialized? Thanks.
Because you have var interval inside beginTimer, the interval variable inside beginTimer will always reference the local variable, which is distinct from the outer interval (which is never touched). Once beginTimer ends, the local interval variable will simply be garbage collected. Leave off the var to assign to the outer variable instead:
var interval = null;
function beginTimer() {
interval = setInterval(function(){
var intervalinside the beginTimer() is error.
var seconds = 0, minutes = 0;
var timer = document.querySelector("#timer");
var interval = null;
function beginTimer() {
// var interval = setInterval(function(){
interval = setInterval(function(){
timer.innerHTML = minutes + " Minute(s) " + seconds + " Seconds";
seconds++;
if(seconds == 60) {
minutes++;
seconds = 0;
}
else if(minutes == 60) {
return "Out of time!";
}
}, 1000);
}
You need also to reset the ongoing timer before starting a new one. Please try the following:
var interval;
function beginTimer() {
clearInterval(interval);
interval = setInterval(function(){
...

timer implementation in javascript

I had written following code for implementing a timer in JS. But the issue is, for the subsequent recursive calls, the method throws reference error for timeChkSplitTime. How does it happen as its being passed in settimeout().
Also, later I used the easy timer js lib for this. If possible, pls provide an idea to configure the timer for minutes and seconds alone.
function timeChkold(timeChkSplitTime) {
var min = timeChkSplitTime[0], sec = timeChkSplitTime[1];
if (!(timeChkSplitTime[0]==0 && splitTime[1]==0)) {
var strSec, strMin = "0"+min.toString();
if (sec < 10) strSec = "0"+ sec.toString();
else strSec = sec.toString();
$(".timer-btn time").html(strMin+":"+strSec);
timeChkSplitTime[0]=0;
if (sec > 0) timeChkSplitTime[1]--;
else timeChkSplitTime[1] = 59;
setTimeout( "timeChk(timeChkSplitTime);", 1000);
}
else {
var startBtn = $(".start-btn");
startBtn.html("Start");
startBtn.css( {
"border": "1px solid #56B68B",
"background": "#56B68B",
});
var startTime = "01:00";
$(".timer-btn time").html(startTime);
}
}
setTimeout( "timeChk(timeChkSplitTime);", 1000);
should be
setTimeout( timeChk(timeChkSplitTime), 1000);
Variables aren't parsed through strings, on the line with the code:
setTimeout( "timeChk(timeChkSplitTime);", 1000);
It's literally reading the parameter as the value as the text timeChkSplitTime and not the value of the variable timeChkSplitTime. Other than using a string use a function for setTimeout:
setTimeout( timeChk(timeChkSplitTime), 1000);
your code is a little bit of a spaghetti code. you should seperate your code logic from the view. split them into functions. and most importantly, using setTimeout is not efficient in this case.
var CountdownTimer = function(startTime) {
var timeInSeconds = this.stringToSeconds(startTime);
this.original = timeInSeconds;
this.time = timeInSeconds;
this.running = false;
}
CountdownTimer.prototype.start = function(callback) {
this.running = true;
this.interval = setInterval(function() {
if(this.time < 1) {
this.running = false;
clearInterval(this.interval);
} else {
this.time -= 1;
callback();
}
}.bind(this), 1000);
}
CountdownTimer.prototype.pause = function() {
if(this.running) {
this.running = false;
clearInterval(this.interval);
}
}
CountdownTimer.prototype.restart = function() {
this.time = this.original;
}
CountdownTimer.prototype.stringToSeconds = function(timeSting) {
var timeArray = timeSting.split(':');
var minutes = parseInt(timeArray[0], 10);
var seconds = parseInt(timeArray[1], 10);
var totalSeconds = (minutes*60) + seconds;
return totalSeconds;
}
CountdownTimer.prototype.secondsToStrings = function(timeNumber) {
finalString = '';
var minutes = parseInt(timeNumber/60, 10);
var seconds = timeNumber - (minutes*60);
var minStr = String(minutes);
var secStr = String(seconds);
if(minutes < 10) minStr = "0" + minStr;
if(seconds < 10) secStr = "0" + secStr;
return minStr + ":" + secStr;
}
to run this code you can add the following
var countdownTest = new CountdownTimer("01:15");
countdownTest.start(onEachTick);
function onEachTick() {
var time = countdownTest.secondsToStrings(countdownTest.time);
console.log(time)
}
you can write your custom code in the onEachTick funciton.
you can check if the timer is running by typing countdownTest.running.
you can also restart and pause the timer. now you can customize your views however you want.

Changer SetInterval Values After Interval

If I can try to make everyone understand what I am looking for, I am looking for the value of the interval to change to lets say "5000ms" after "1000ms" and then it would go on to the next value such as "2000ms" and repeat all over again! The current code I have is pretty much a stopwatch, It adds the number 1 to a paragraph every 1000ms. Any help is extremely appreciated!
<script>
function myFunction() {
clicks += 1;
}
setInterval(myFunction, 1000);
var clicks = 0;
function myFunction() {
clicks += 1;
document.getElementById("demo").innerHTML = clicks;
// connects to paragraph id
}
</script>
<p id="demo"></p>
<!--connects to getElementById-->
Don't use setInterval - this functions will perform the action in any given interval, which you set once.
Use setTimeout instead. Which performs the action only once after given interval, and then call it again and again with different interval values.
what about this
<script>
var clicks = 0;
myFunction(1000);
function myFunction( currentInterval ) {
clicks ++;
document.getElementById("demo").innerHTML = clicks;
if ( currentInterval == 1000 )
{
currentInterval = 5000;
}
else if ( currentInterval == 5000 )
{
currentInterval = 2000;
}
else
{
currentInterval = 1000;
}
setTimeout( function(){ myFunction( currentInterval ) }, currentInterval );
}
</script>
<p id="demo"></p>
you should try using recursive timeout instead of interval
var timeout = 1000;
var timer;
function startTimer() {
clearTimeout(timer);
timer = setTimeout(function() {
console.log('tick');
startTimer();
}, timeout);
}
startTimer();
// timeout = 2000
// timeout = 500
// clearTimeout(timer); to cancel
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
This might look a little complicated but you can try something like this:
JSFiddle.
(function() {
var interval = null;
var limit = 5;
function initInterval(callback, index) {
var msToSec = 1000;
if (interval) {
clearInterval();
}
console.log("Delay: ", index)
interval = setInterval(callback, index * msToSec);
}
function clearInterval() {
window.clearInterval(interval);
interval = null;
}
function resetInterval(callback, count) {
clearInterval();
initInterval(callback, count);
}
function main() {
var count = 1;
var notify = function() {
console.log("Hello World: ", count);
var _nextCount = ((count++) % limit) + 1;
if (count < 10) {
resetInterval(notify, _nextCount);
} else {
console.log("Stoping loop...");
clearInterval();
}
}
initInterval(notify, count);
}
main()
})()

setInterval countDown update time

I have this countDown, each time I press the buttons I want to add 5 more seconds.
When the time is updated the function count down the new value but the old value as well.
Can someone explain me why?
http://jsfiddle.net/xqdj3uz8/1/
$('button').on('click', function() {
var newtime = parseInt(seconds + 5);
timer(newtime);
});
You could try by using a global variable to track the amount of seconds left. Clicking on the button will increment this variable.
var timeLeft = 10;
function timer() {
var i = setInterval(function () {
$('span').text(timeLeft);
timeLeft--
if (timeLeft === 0) clearInterval(i)
}, 1000)
}
function addSeconds(n) {
timeLeft += n
}
timer()
$('button').on('click', function () {
addSeconds(5)
});
Demo (1): http://jsfiddle.net/xqdj3uz8/21/
please use it
function timer(time) {
var interval = setInterval(countDown, 1000);
function countDown() {
time--;
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
}
$('button').on('click', function() {
time=parseInt(time + 5);
$('span').text(time);
});
}
var seconds = 5;
timer(seconds);
Try This
Working JSFIDDLE
var gblTime=0;
function timer(time) {
var interval = setInterval(countDown, 1000);
gblTime = time;
function countDown() {
gblTime--;
$('span').text(gblTime);
if(gblTime <= 0) {
clearInterval(interval);
}
}
}
var seconds = 5;
timer(seconds);
$('button').on('click', function() {
gblTime = parseInt(gblTime +1+ 5);
//timer(newtime);
});
You are adding new intervals that are independent form each other, try:
var time = 5;
var seconds = 5;
function timer() {
var interval = setInterval(countDown, 1000);
function countDown() {
$('span').text(time);
if(time === 0) {
clearInterval(interval);
}
time--;
}
}
timer();
$('button').on('click', function() {
if(time==0){
timer();
}
time += seconds;
});

Categories

Resources