How to stop javascript from executing after clicking stop button? - javascript

<script>
function timer(duration, elementId, scoreID, mistakesID){
var start = Date.now();
var min, sec, diff;
var scoreComputed = false;
function timerCompute(){
diff = duration - (((Date.now() - start) / 1000) | 0);
min = ( diff / 60 ) | 0;
sec = ( diff % 60 ) | 0;
//If less than 10, add zero in front of it to keep tens place
min = min < 10 ? "0" + min : min;
sec = sec < 10 ? "0" + sec : sec;
elementId.textContent = min + ":" + sec;
if ( diff <= 0 ){
elementId.textContent = "0:00";
if (!scoreComputed){
score /= (duration / 60);
score = Math.round(score);
scoreComputed = true;
}
scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
if(mistakes.length > 0){
var mistakesStr = "";
for(var i = 0; i < mistakes.length; i++){
mistakesStr += i > 0 ? ", " : "";
usertextArr[mistakes[i]] = usertextArr[mistakes[i]] === "" ? "blank" : usertextArr[mistakes[i]];
mistakesStr += usertextArr[mistakes[i]] + " instead of " + textArr[mistakes[i]];;
}
mistakesID.textContent = mistakesStr;
$("#mistakesContainer").fadeIn(1500);
$('.type-test-wrapper').css("filter","blur(3px)");
}
return;
}
};
timerCompute();
setInterval(timerCompute, 1000);
}
var timerStarted = false;
$('#usertext').on('keydown', function() {
var time = 60 * 0.1,
display = document.querySelector('#time');
scoreDisplay = document.querySelector('#score');
mistakesDisplay = document.querySelector('#mistakes');
if ( timerStarted === false ){
timer(time, display, scoreDisplay, mistakesDisplay);
typeTest();
timerStarted = true;
}
});
</script>
The above script is from a typing test. When the typing test ends, the above script fades in a result box. I was trying to modify the code. I want to add a close button to the result box so that user can close the box after he viewed the result. So I added the below code to close the result box.
<script type='text/javascript'>
jQuery(document).ready(function($){
$('.close-btn, body').click(function(){
$('.type-test-wrapper').css("filter","blur(0px)");
$('#resultsContainer, #mistakesContainer').stop().fadeOut('medium');
});
});
</script>
The problem I am facing is that when I click on close button, the box fades out #resultContainer, #mistakesContainer but as soon the box gets faded, it again fades in. No matter how many times i close the box, it fades in again and again. I want that once user click on close button the box should not get displayed again. How to fix the code so that once the the box fades out, the first code doesn't again fades in the box. I am new at javascript. Thank you for help.
Live webpage here https://htmlpreview.github.io/?https://raw.githubusercontent.com/dp121112/type-testing/master/test.html

I think you're not clearing the interval
try to assing interval as follow.
var intrvl= setInterval(timerCompute, 1000);
and clear it when its done
scoreID.textContent = score;
document.getElementById("usertext").readOnly = true;
$("#resultsContainer").fadeIn(1500);
clearInterval(intrvl);

Related

Showing multiple timer function in Angular.js

I am trying to display two timer on a webpage with different start times.
First timer only shows for 5 seconds and then after 10 seconds I need to show timer2.
I am very new to Angular and have put together following code.
It seems to be working fine except when the settimeout is called the third time it doesn't work correctly and it starts going very fast.
Controller
// initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';
$scope.ti = 0;
$scope.startTimer1 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer1 = min + ":" + sec;
mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}
//start timer 1
$scope.startTimer1();
$scope.$watch('timer1',function(){
if($scope.timer1 !=undefined){
if($scope.timer1 =='00:05'){
$timeout.cancel(mytimeout1);
setInterval(function(){
$scope.startTimer2()
$scope.ti = 0;
},1000)
}
}
})
//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer2 = min + ":" + sec;
mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}
$scope.$watch('timer2',function(){
if($scope.timer2 !=undefined){
if($scope.timer2 =='00:05'){
$timeout.cancel(mytimeout2);
setInterval(function(){
$scope.startTimer1();
$scope.ti = 0;
},1000)
}
}
})
In my view I simply have
<p>{{timer1}}</p>
<p>{{timer2}}</p>
You're basically starting multiple startTimer function so it's adding up. If i understood your problem well you don't even need to have all those watchers and timeouts.
You just can use $interval this way :
$scope.Timer = $interval(function () {
++$scope.tickCount
if ($scope.tickCount <= 5) {
$scope.timer1++
} else {
$scope.timer2++
if ($scope.tickCount >= 10)
$scope.tickCount = 0;
}
}, 1000);
Working fiddle

switching players when countdown hits 0 with javascript and jquery

my code is all about changing players/streams
here's my plnkr http://plnkr.co/edit/nV10XXQI2QStydCIYuyQ?p=preview some how it doesn't work currectly on plnkr but here's my page witth same code http://tgo-tv.com/test/page1.php
how ever, as you see when you go to the page , first countdown starts from 10 seconds then it will display player. i want to make it like, even when i clicked on any video buttons like Video 1 or Video 2 etc.. it should start countdown for new player
here's my js code hope ou understand
<script>
function startChecking() {
secondsleft -= 1e3, document.querySelector(".load_video").innerHTML = "Please Wait.. " + Math.abs(secondsleft / 1e3) + " Seconds", 0 == secondsleft && (clearInterval(interval), $(".reloadframe").show(), document.querySelector(".load_video").style.display = "none", document.querySelector(".frame_src").style.display = "", document.querySelector(".frame_src").src = document.querySelector(".frame_src").getAttribute("data-src"), $("#btn_click_to_play").hide())
}
function startschedule() {
document.querySelector(".frame_src").src = "about:blank";
clearInterval(interval), secondsleft = threshold, document.querySelector(".load_video").innerHTML = "Please Wait.. " + Math.abs(secondsleft / 1e3) + " Seconds", interval = setInterval(function() {
startChecking()
}, 1e3)
}
function resetTimer() {
startschedule()
}
var timeout, interval, threshold = 1e4,
secondsleft = threshold;
window.onload = function() {
startschedule()
};
</script>

HTML5 Audio player, make pause and play on time out

How do i edit this code below so that the activeSong.Play() will only occur for 10 seconds, then it will trigger the activeSong.pause() event
I have tried to code it but i thought it would be easier to post the clean code rather than my butchered attempt
<script type="text/javascript">
var activeSong;
//Plays the song. Just pass the id of the audio element.
function play(id){
//Sets the active song to the song being played. All other functions depend on this.
activeSong = document.getElementById(id);
//Plays the song defined in the audio tag.
activeSong.play();
//Calculates the starting percentage of the song.
var percentageOfVolume = activeSong.volume / 1;
var percentageOfVolumeMeter = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;
//Fills out the volume status bar.
document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + "px";
}
//Pauses the active song.
function pause(){
activeSong.pause();
}
//Does a switch of the play/pause with one button.
function playPause(id){
//Sets the active song since one of the functions could be play.
activeSong = document.getElementById(id);
//Checks to see if the song is paused, if it is, play it from where it left off otherwise pause it.
if (activeSong.paused){
activeSong.play();
}else{
activeSong.pause();
}
}
//Updates the current time function so it reflects where the user is in the song.
//This function is called whenever the time is updated. This keeps the visual in sync with the actual time.
function updateTime(){
var currentSeconds = (Math.floor(activeSong.currentTime % 60) < 10 ? '0' : '') + Math.floor(activeSong.currentTime % 60);
var currentMinutes = Math.floor(activeSong.currentTime / 60);
//Sets the current song location compared to the song duration.
document.getElementById('songTime').innerHTML = currentMinutes + ":" + currentSeconds + ' / ' + Math.floor(activeSong.duration / 60) + ":" + (Math.floor(activeSong.duration % 60) < 10 ? '0' : '') + Math.floor(activeSong.duration % 60);
//Fills out the slider with the appropriate position.
var percentageOfSong = (activeSong.currentTime/activeSong.duration);
var percentageOfSlider = document.getElementById('songSlider').offsetWidth * percentageOfSong;
//Updates the track progress div.
document.getElementById('trackProgress').style.width = Math.round(percentageOfSlider) + "px";
}
function volumeUpdate(number){
//Updates the volume of the track to a certain number.
activeSong.volume = number / 100;
}
//Changes the volume up or down a specific number
function changeVolume(number, direction){
//Checks to see if the volume is at zero, if so it doesn't go any further.
if(activeSong.volume >= 0 && direction == "down"){
activeSong.volume = activeSong.volume - (number / 100);
}
//Checks to see if the volume is at one, if so it doesn't go any higher.
if(activeSong.volume <= 1 && direction == "up"){
activeSong.volume = activeSong.volume + (number / 100);
}
//Finds the percentage of the volume and sets the volume meter accordingly.
var percentageOfVolume = activeSong.volume / 1;
var percentageOfVolumeSlider = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;
document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + "px";
}
//Sets the location of the song based off of the percentage of the slider clicked.
function setLocation(percentage){
activeSong.currentTime = activeSong.duration * percentage;
}
/*
Gets the percentage of the click on the slider to set the song position accordingly.
Source for Object event and offset: http://website-engineering.blogspot.com/2011/04/get-x-y-coordinates-relative-to-div-on.html
*/
function setSongPosition(obj,e){
//Gets the offset from the left so it gets the exact location.
var songSliderWidth = obj.offsetWidth;
var evtobj=window.event? event : e;
clickLocation = evtobj.layerX - obj.offsetLeft;
var percentage = (clickLocation/songSliderWidth);
//Sets the song location with the percentage.
setLocation(percentage);
}
//Set's volume as a percentage of total volume based off of user click.
function setVolume(percentage){
activeSong.volume = percentage;
var percentageOfVolume = activeSong.volume / 1;
var percentageOfVolumeSlider = document.getElementById('volumeMeter').offsetWidth * percentageOfVolume;
document.getElementById('volumeStatus').style.width = Math.round(percentageOfVolumeSlider) + "px";
}
//Set's new volume id based off of the click on the volume bar.
function setNewVolume(obj,e){
var volumeSliderWidth = obj.offsetWidth;
var evtobj = window.event? event: e;
clickLocation = evtobj.layerX - obj.offsetLeft;
var percentage = (clickLocation/volumeSliderWidth);
setVolume(percentage);
}
//Stop song by setting the current time to 0 and pausing the song.
function stopSong(){
activeSong.currentTime = 0;
activeSong.pause();
}
</script>

Is there a way to remove all the functions in javascript when timeout?

I have created a drag and drop game. Is there a possible way to stop all the mouseEvents when the time is out?
Below are my codes for the timer.
var canvas = document.getElementById("canvas");
var canvas_context = canvas.getContext("2d");
var text = "you have: 10 : 00 left"
function showFillText() {
canvas_context.clearRect(500, 350, 80, 100);
canvas_context.fillStyle = '#36F'; //text color
canvas_context.font = ' bold 20px sans-serif';
canvas_context.textBaseline = 'bottom';
canvas_context.fillText(text, 500, 450); //('text', x, y)
}
var mins = .1; //Set the number of minutes you need
var secs = mins * 60;
var currentSeconds = 0;
var currentMinutes = 0;
setTimeout('Decrement()',1000);
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if(currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
text = currentMinutes + ":" + currentSeconds; //Set the element id you need the time put into.
if(secs !== -1) setTimeout('Decrement()',1000);
//document.getElementById("timerText").innerHTML = currentMinutes + ":" + currentSeconds;
if (currentMinutes == 0 && currentSeconds ==0) {
text = "TIMES UP"
//document.location.href = "http://www.google.com";
}
showFillText()
}
Keep a list of all your event handlers and delete them when your timer expires.
So instead of:
document.getElementById("some element").addEventListener("onX", function () {});
you do:
registerEvent(document.getElementById("some element"), "onX", function () {});
registerEvent keeps a list of all your event listeners. You can remove event listeners with removeEventListener.
It is possible using pointer-events. Use it against a div or class you are interested in. http://caniuse.com/pointer-events
Add a flag called (eg) 'lock', initially set to 0.
When the time is up, set it to 1.
add an if within the function
function myFunction(){
if( lock == 0 ){
... function ...
}
}
There might be a more sophisticated way of doing it but that should work . . .

how to change the the margin value with a count down?

Would anyone be able to help me with this?
Here is what I have now
http://jsfiddle.net/fergu0516/GAVDA/
var leave = 200;
if(leave > 0)
{
CounterTimer();
}
function CounterTimer()
{
var minute = Math.floor(leave / 60);
var second = Math.floor(leave) - (minute*60);
minute=minute<10 ? "0" + minute : minute;
second=second<10 ? "0" + second : second;
var remain = minute + ":" + second;
leave = leave-1 ;
document.getElementById("clkTimer").innerHTML = remain;
if(leave >= 0)
{
setTimeout(CounterTimer,1000);
}
else
{
alert("Your cart is expired!")
window.location = "#";
}
}
$(document).ready(function(){
// The relative URL of the submit.php script.
// You will probably have to change it.
// Caching the feedback object:
var feedback = $('#feedback');
$('#feedback').click(function(){
// We are storing the values of the animated
// properties in a separate object:
var anim = {
mb : 207, // Margin Bottom
pt : 0 // Padding Top
};
var el = $(this).find('.arrow');
if(el.hasClass('buttonright')){
anim = {
mb : 0,
pt : 0
};
}
// The first animation moves the form up or down, and the second one
// moves the "Feedback heading" so it fits in the minimized version
feedback.stop().animate({marginRight: anim.mb});
feedback.find('.section').stop().animate({paddingTop:anim.pt},function(){
el.toggleClass('buttonright buttonleft');
});
});
});
I need to have the same effect as the sample: what happens now is that when I press the red box the timer shows by giving the (div id="feedback") a margin-right of 207px.
What I need here is this to happen automatically when the time hits 1:00. So when the timer hits 1:00 the window will show, by adding margin-right:207px to the object.
Thank you so much, anything would help.
Demo
do something like this:
if(leave == 60){
$('#feedback').trigger('click');
}
Add
if (leave == 60)
{
$('#feedback').stop().animate({marginRight: 207});
}
to the CounterTimer() function. Maybe after the leave = leave - 1; line.
All you need to do is add an if statement to find out if(leave == 60), and if so you can then animate the element to its "visible" margin-right value.

Categories

Resources