stop interval inside a function - javascript

I have this script that runs a soccer game clock,
when I click the start button everything is working properly
but I can't stop the clock.
var count;
function gameClock() {
var minutesLabel = document.getElementById("minutes");
var secondsLabel = document.getElementById("seconds");
var totalSeconds = 0;
var count = setInterval(function() {
setTime()
}, 1000);
function setTime() {
++totalSeconds;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
}
//Start Stop Game Clock
$(document).on('click', '#f_start', function() {
$("#half_name").text('FIRST HALF');
gameClock();
// localStorage.setItem('first_half_click', getTime());
// localStorage.setItem('half', 1);
})
$(document).on('click', '#f_stop', function() {
clearInterval(count);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="col-2">
<button class="btn btn-success" id="f_start"> START</button>
</div>
<div class="col-2">
<button class="btn btn-danger" id="f_stop"> STOP</button>
</div>

You are redeclaring the count global variable inside the gameClock method which means it's scope is only in that function. change the assignment to use the global count variable instead of the useless local variable.
var count = setInterval(function() {
setTime()
}, 1000);
//to
count = setInterval(function() {
setTime()
}, 1000);

Related

pass value from span tag to input tag

I have a counter in span tags, when I press Start the timer starts counting and when pressing Pause it is stopped. Now the question is, How do I pass the value from the counter to input tag when Pause clicked?
<span id="min">00</span>:<span id="sec">00</span>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
Script
<script>
const Clock = {
totalSeconds: 0,
start: function () {
if (!this.interval) {
const self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function () {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
pause: function () {
clearInterval(this.interval);
delete this.interval;
},
};
document.getElementById("startButton").addEventListener("click", function () { Clock.start(); });
document.getElementById("pauseButton").addEventListener("click", function () { Clock.pause(); });
</script>
Here it is as a runnable snippet:
const Clock = {
totalSeconds: 0,
start: function() {
if (!this.interval) {
const self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function() {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
pause: function() {
clearInterval(this.interval);
delete this.interval;
},
};
document.getElementById("startButton").addEventListener("click", function() {
Clock.start();
});
document.getElementById("pauseButton").addEventListener("click", function() {
Clock.pause();
});
<span id="min">00</span>:<span id="sec">00</span>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
I adjustment your script with template string javascript created with a variable time and improvement your double tags for a tag with id "time-span" and "time-input" both with return variable time
Also in Clock inserted pad function property and acess inside start with self variable
See this code and working
Update
Improvement with new input time last show time after pause.
const Clock = {
totalSeconds: 0,
time: null,
pad: function (val) {
return val > 9 ? val : "0" + val;
},
start: function () {
const self = this;
if (!self.interval) {
self.interval = setInterval(function () {
self.totalSeconds += 1;
let min = self.pad(Math.floor(self.totalSeconds / 60 % 60));
let sec = self.pad(parseInt(self.totalSeconds % 60));
self.time = `${min}:${sec}`;
document.getElementById("time-span").innerHTML = self.time;
document.getElementById("time-input").value = self.time;
}, 1000);
}
},
createInputResult: function () {
const self = this;
let input = document.createElement('input');
let line = document.createElement('hr');
input.id = 'time-result';
input.type = 'text';
input.value = self.time;
document.getElementById("pauseButton").insertAdjacentElement('afterend', input);
document.getElementById("pauseButton").insertAdjacentElement('afterend', line);
},
pause: function () {
const self = this;
clearInterval(self.interval);
delete self.interval;
self.createInputResult();
},
};
document.getElementById("startButton").addEventListener("click", () => Clock.start() );
document.getElementById("pauseButton").addEventListener("click", () => Clock.pause() );
<!-- Times -->
<span id="time-span">00:00</span>
<input id="time-input" type="text" value="00:00">
<!-- Controls -->
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">
const Clock = {
totalSeconds: 0,
start: function() {
if (!this.interval) {
const self = this;
function pad(val) {
return val > 9 ? val : "0" + val;
}
this.interval = setInterval(function() {
self.totalSeconds += 1;
document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
}, 1000);
}
},
pause: function() {
clearInterval(this.interval);
var text = document.getElementById('sec').innerHTML
document.getElementById('startButton').value=text;
delete this.interval;
},
};
document.getElementById("startButton").addEventListener("click", function() {
Clock.start();
});
document.getElementById("pauseButton").addEventListener("click", function() {
Clock.pause();
});
<span id="min">00</span>:<span id="sec">00</span>
<input id="startButton" type="button" value="Start">
<input id="pauseButton" type="button" value="Pause">

The stop button for my pomdoro clock does not function

I am building a pomodoro clock with start and stop button. I have the start button functioning, but not the stop button. Here is my code:
HTML:
<h1> Pomodoro Clock</h1>
<!--Place holder for timer-->
<div id="timer" class="circle">Timer</div>
<!--//Start Button-->
<button onclick="setTimeout(timer, 1000);">Start</button>
<!--Stop Button-->
<button onclick="timer.stopTimer()">Stop</button>
JS:
var i = 1500;
var timeHandler;
document.getElementById("timer").innerHTML = i;
function timer() {
timeHandler = setInterval(function() {
if (i > 0) {
i--;
document.getElementById("timer").innerHTML = i;
}
}, 1000);
function stopTimer() {
clearTimeout(timeHandler);
}
}
I would prefer a vanilla JS solution.
Try this:
HTML
<!--Stop Button-->
<button onclick="stopTimer()">Stop</button>
JS
var i = 1500;
var timeHandler;
document.getElementById("timer").innerHTML = i;
function timer() {
timeHandler = setInterval(function() {
if (i > 0) {
i--;
document.getElementById("timer").innerHTML = i;
}
}, 1000);
}
function stopTimer() {
clearTimeout(timeHandler);
}

Timer is not getting reset using clearInterval()

This is my Timer function
var myTimer = setInterval(function () {
var d = new Date();
var seconds = d.getMinutes() * 60 + d.getSeconds();
var fiveMin = 60 * 5;
var timeleft = fiveMin - seconds % fiveMin;
var result = parseInt(timeleft / 60) + ':' + timeleft % 60;
//console.log(result);
var timerObj = {
timer : result
}
$scope.timerArray = timerObj;
$scope.$apply();
if (timeleft === 1) {
$scope.statusDetails = [];
$scope.timeDetails();
$scope.get_dbStatus();
}
}, 1000);
This function will reset the above timer when I click a button.
$scope.refreshStatusList = function(){
$scope.hide = true;
$scope.$emit('LOAD');
clearInterval(myTimer);
$scope.statusDetails = [];
$scope.timeDetails();
$scope.get_dbStatus();
};
This is my refresh button in html page upon clicking it the timer must get reset.
<div class="col-lg-2">
<a href="#" title="Refresh" ng-click="refreshStatusList();">
<i class="fa fa-refresh fa-lg"></i>
</a>
</div>
Since, you are using angularjs, You should use $interval directive, which will internally call $scope.apply()
Usage
$scope.intervalPromise = $interval(function () {
//Your code
}, 1000);
To clear interval
$interval.cancel($scope.intervalPromise);
Try using this
$scope.apply();

stopwatch clear variable javascript

Hey all I'm extremely unfamiliar in using javascript... I just need help clearing the time (this should stop the time then clear it) in my script. See: function clear() thanks :) if you have any suggestions in merging the stop\start button into one function that'd be appreciated too. thank you again!
<script type='text/javascript'>
var clsStopwatch = function () {
var startAt = 0;
var lapTime = 0;
var now = function () {
return (new Date()).getTime();
};
this.start = function () {
startAt = startAt ? startAt : now();
};
this.stop = function () {
lapTime = startAt ? lapTime + now() - startAt : lapTime;
startAt = 0;
};
this.time = function () {
return lapTime + (startAt ? now() - startAt : 0);
};
};
var x = new clsStopwatch();
var $time;
var clocktimer;
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
m = Math.floor(time / (60 * 1000));
time = time % (60 * 1000);
s = Math.floor(time / 1000);
ms = time % 1000;
newTime = pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
return newTime;
}
function show() {
$time = document.getElementById('time');
update();
}
function update() {
$time.innerHTML = formatTime(x.time());
}
function start() {
clocktimer = setInterval("update()", 1);
x.start();
}
function stop() {
x.stop();
document.getElementById('counter').value = formatTime(x.time());
clearInterval(clocktimer);
}
function clear() {
x.stop();
????????? this is the function i need help on
}
</script>
html:
<body onload="show();">
<form action="submit.php" method="post"/>
Time: <span id="time"></span><br/>
<!--<input type="text" name-"time">-->
<input type="button" value="Start" onclick="start();">
<input type="button" value="Stop" onclick="stop();">
<input type="button" value="Clear" onclick="clear();">
<input type="submit" value="Save" onclick="stop();">
<br/><br/>
You, forgot to put show() in the start() function
Here is the working fiddle http://jsfiddle.net/64gFm/
Change the clear() function to clearWatch() as clear is an inbult function
New Updated Js Fiddle http://jsfiddle.net/64gFm/1/
function clearWatch() {
x.stop();
x.clear();
clearInterval(clocktimer);
update();
}
Hope, it may help you. Have anice day. :)

Adding start, stop, and reset buttons for a timer

I'm making a timer and have it working already one load. I want to add a start, stop, and reset button to it. This is my code as is atm.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'),
minutesLabel = document.getElementById('minutes'),
hoursLabel = document.getElementById('hours'),
totalSeconds = 0,
startButton = document.getElementById('start'),
resetButton = document.getElementById('reset'),
onOff = 0;
startButton.onclick = function() {
onOff = 1;
};
resetButton.onclick = function() {
totalSeconds = 0;
onOff = 0;
};
if ( onOff == 1 ) {
setInterval( setTime, 1000 );
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad( totalSeconds % 60 );
minutesLabel.innerHTML = pad( parseInt( totalSeconds / 60 ) );
hoursLabel.innerHTML = pad( parseInt( totalSeconds / 3600 ) )
}
function pad( val ) {
var valString = val + "";
if( valString.length < 2 ) {
return "0" + valString;
} else {
return valString;
}
}
}
})();
The buttons are not working atm however. I'm not sure if this the best solution for the goal as well, so suggestions are welcome.
(function() {
"use strict";
var secondsLabel = document.getElementById('seconds'), minutesLabel = document.getElementById('minutes'), hoursLabel = document
.getElementById('hours'), totalSeconds = 0, startButton = document.getElementById('start'), stopButton = document.getElementById('stop'), resetButton = document
.getElementById('reset'), timer = null;
startButton.onclick = function() {
if (!timer) {
timer = setInterval(setTime, 1000);
}
};
stopButton.onclick = function() {
if (timer) {
clearInterval(timer);
timer = null;
}
};
resetButton.onclick = function() {
if (timer) {
totalSeconds = 0;
stop();
}
};
function setTime() {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds % 60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds / 60));
hoursLabel.innerHTML = pad(parseInt(totalSeconds / 3600))
}
function pad(val) {
var valString = val + "";
if (valString.length < 2) {
return "0" + valString;
} else {
return valString;
}
}
})();
<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;
function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}
function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}
function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()" />
<input type="text" id="txt" />
<input type="button" value="Stop count!" onclick="stopCount()" />
</form>
<p>
Click on the "Start count!" button above to start the timer. The input field will count forever, starting at 0. Click on the "Stop count!" button to stop the counting. Click on the "Start count!" button to start the timer again.
</p>
</body>
</html>

Categories