About the relation ship between A driven event and multithreading - javascript

While i was doing this try it yourself on W3Schools:
<!DOCTYPE html>
<html>
<body>
<button onclick="startCount()">Start count!</button>
<input type="text" id="txt">
<button onclick="stopCount()">Stop count!</button>
<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>
<script>
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c + 1;
t = setTimeout(function(){ timedCount() }, 1000);
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
</script>
</body>
</html>
I noticed that I had a question deep in me that I had never asked before
In this tutorial, the timedCount() kept calling itself and it will never stop.
and obviously. When you click stop the recursion stops
kindly point the key to me.
I thought the program should have ran for ever, which means that it wont accept any driven event by the button
Thanks.

It does not actually “run forever”, it's just a way of seeing it. Actually, it reschedules itself to run again in 1000 milliseconds.
But when clicking the button, stopCount is called, which discards the current rescheduling (clearTimeout(t);)

Related

JavaScript with Timeout Function

I am trying to display a counter at the element with #showText as ID. However, no matter what, the #showText element never appear. I have explanations of the codes below. Can anyone help me to make the #showText element display?
var counter = 0;
// Call the update function 2 seconds after first load.
timeoutID = window.setTimeout("Update();", 2000);
function Update() {
counter++;
var textField = document.getElementById("showText");
/* The value counter changes once every 2 seconds. */
textField.innerHtml = "The counter is now at " + counter;
// Set another timeout for the next count, function calls itself.
timeoutID = window.setTimeout("Update();", 2000);
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", function() {
counter = 0; // Reset counter to 0.
Update(); // Call Update() method to start counting from 0.
});
// Clears time out for timeID, which means Update() will no longer be invoked, and counter stops increasing.
document.getElementById("stop").addEventListener("click", function() {
window.clearTimeout(timeoutID);
});
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
change setTimeout("Update();", 2000) to setTimeout(Update, 2000)
change innerHtml to innerHTML
var counter = 0;
// Call the update function 2 seconds after first load.
timeoutID = window.setTimeout(Update, 2000);
function Update() {
counter++;
var textField = document.getElementById("showText");
/* The value counter changes once every 2 seconds. */
textField.innerHTML = "The counter is now at " + counter;
// Set another timeout for the next count, function calls itself.
timeoutID = window.setTimeout(Update, 2000);
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", function() {
counter = 0; // Reset counter to 0.
Update(); // Call Update() method to start counting from 0.
});
// Clears time out for timeID, which means Update() will no longer be invoked, and counter stops increasing.
document.getElementById("stop").addEventListener("click", function() {
window.clearTimeout(timeoutID);
});
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
Your textField.innerHTML had a syntax error; you wrote innerHtml. I also removed the orphan function call, as you would want it to only run on button press I presume. Correcting that, now it works -the STOP button as well -:
var counter = 0;
function Update() {
counter++;
var textField = document.getElementById("showText");
/* The value counter changes once every 2 seconds. */
textField.innerHTML = "The counter is now at " + counter;
// Set another timeout for the next count, function calls itself.
timeoutID = window.setTimeout("Update();", 2000);
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", function() {
counter = 0; // Reset counter to 0.
Update(); // Call Update() method to start counting from 0.
});
// Clears time out for timeID, which means Update() will no longer be invoked, and counter stops increasing.
document.getElementById("stop").addEventListener("click", function() {
window.clearTimeout(timeoutID);
});
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
You can:
use setInterval rather than setTimeout;
innerHTML or innerText rather than the (invalid) innerHtml;
separate out the logic for starting, stopping, showing the counter and updating the counter to make it clearer what is being run and when and to make sure you do not have additional timers spawned:
var counter = 0;
var isCounting = false;
var timeoutID = null;
var textField = document.getElementById("showText");
function Stop() {
if ( timeoutID )
{
self.clearInterval( timeoutID );
}
}
function Start()
{
Stop();
counter = 0;
timeoutID = self.setInterval(Update, 2000);
Show();
}
function Show()
{
textField.innerText = counter;
}
function Update() {
counter++;
Show();
}
// Set event listeners for the buttons.
document.getElementById("restart").addEventListener("click", Start );
document.getElementById("stop").addEventListener("click", Stop );
<h1>Timeout Example</h1>
<p>The counter will update every two seconds. </p>
<p>Press RESTART or STOP to restart or stop the count. </p>
<p id="showText"></p>
<section>
<button type="button" id="restart">RESTART</button>
<button type="button" id="stop">STOP</button>
</section>
There is only a single change that has to be done in you code to make it work as expected.
Just replace the below function block and run the code:
function Update() {
counter++;
document.getElementById("showText").innerHTML = "The counter is now at!" + counter;
timeoutID = window.setTimeout("Update();", 2000);
}
this solution should work for you.

Pause countdown timer (JavaScript)

I want the countdown timer to pause when I click the pause button, and start from where it left off when I click the go button. It'd also be good if the go button enables again when reset is clicked, but as of now it continues being disabled for as long as the timer was set.
For pausing, I tried what I saw in this fiddle but it didn't work. I also tried this to no avail:
$("#pause").click(function() {
clearInterval(count());
})
Here's the fiddle.
Thanks!
Here you have solution of working countdown: http://jsfiddle.net/XcvaE/4/
<script>
var CCOUNT = 60;
var t, count;
function cddisplay() {
// displays time in span
document.getElementById('timespan').innerHTML = count;
};
function countdown() {
// starts countdown
cddisplay();
if (count == 0) {
// time is up
} else {
count--;
t = setTimeout("countdown()", 1000);
}
};
function cdpause() {
// pauses countdown
clearTimeout(t);
};
function cdreset() {
// resets countdown
cdpause();
count = CCOUNT;
cddisplay();
};
</script>
<body onload="cdreset()">
<span id="timespan"></span>
<input type="button" value="Start" onclick="countdown()">
<input type="button" value="Stop" onclick="cdpause()">
<input type="button" value="Reset" onclick="cdreset()">
</body>

Javascript auto page refresh code

this is the code that comes in head section and it will automatically refresh the whole page in 1 min as i put 6000 in the code below
<script type="text/javascript">
setTimeout('window.location.href=window.location.href;', 6000);
</script>
is there any way for example, when there's 10 seconds left to refresh the page then, a button will display and say "Click here to reset timer" and it will reset that timer to 1 min again?
<script language="javascript">
var timeout,interval
var threshold = 15000;
var secondsleft=threshold;
startschedule();
window.onload = function()
{
startschedule();
}
function startChecking()
{
secondsleft-=1000;
if(secondsleft <= 10000)
{
document.getElementById("clickme").style.display="";
document.getElementById("timercounter").innerHTML = Math.abs((secondsleft/1000))+" secs";
}
}
function startschedule()
{
clearInterval(timeout);
clearInterval(interval);
timeout = setTimeout('window.location.href=window.location.href;', threshold);
secondsleft=threshold;
interval = setInterval(function()
{
startChecking();
},1000)
}
function resetTimer()
{
startschedule();
document.getElementById("clickme").style.display="none";
document.getElementById("timercounter").innerHTML="";
}
</script>
Please wait...<span id="timercounter"></span>
<button id="clickme" style="display:none;" onclick="javascript:resetTimer();">Click here to reset timer</button>
Assuming you have the following html for the button:
<button id="cancel-reload-button" style="display: none" onclick="cancelReload()">Cancel Reload</button>
And this as the script (Note: this gives the idea, but is not neccesarily fully tested):
// Variable for holding the reference to the current timeout
var myTimeout;
// Starts the reload, called when the page is loaded.
function startReload() {
myTimeout = setTimeout(function() {
document.getElementByID("cancel-reload-button").style.display = "inline";
myTimeout = setTimeout(function() {
window.location.reload();
} 10000)
}, 50000);
}
// Cancel the reload and start it over. Called when the button is
// clicked.
function cancelReload() {
clearTimeout(myTimeout)
startReload()
}
// On page load call this function top begin.
startReload();
I created two functions, one for starting the reload and the second one for cancelling it.
Then I assigned the timeout to the variable myTimeout which can be used to later cancel the timeout.
Then I called myTimeout twice - Once for 50 secs, at which point it shows the button and once for 10 secs after which it finally reloads.
How about below? If you click on OK to reset timer, it would keep giving the confirm box every 50 seconds. If you click cancel, it will refresh the page in 10 seconds.
setInterval(function(){ var r = confirm("Reset Timer");
if (r == true) {
setTimeout('window.location.href=window.location.href;', 60000);
} else {
setTimeout('window.location.href=window.location.href;', 10000);
}
}, 50000);
Note: In your question you specified 1 minute, but your code works for 6 seconds(6000 -- > 6 seconds not 60 seconds) I have included for a minute
You can use 2 setTimeout calls, one to make the "Reset" button show up and another one for the refresh timer reset. The trick is to store the second setTimeout on a global variable and use clearTimeout to reset it if the button is pressed.
Here is some JavaScript code to illustrate:
<script type="text/javascript">
var autoRefreshTime = 30 * 1000; // 60000ms = 60secs = 1 min
var warningTime = autoRefreshTime - (10 * 1000); // 10 secs before autoRefreshTime
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
warningTimeout = setTimeout('ShowResetButton();', warningTime);
function ShowResetButton() {
// Code to make the "Reset" button show up
}
// Make this function your button's onClick handler
function ResetAutoRefreshTimer() {
clearTimeout(waitTimeout);
waitTimeout = setTimeout('window.location.href=window.location.href;', autoRefreshTime);
}
</script>
The way I would do it is make a function with a timeout, and invoke that function
<script type="text/javascript">
var refreshFunc = function(){
setTimeout(function(){
var r = confirm("Do you want to reset the timer?");
if(r === false){
window.location.href=window.location.href;
}else{
refreshFunc();
}
}, 6000);
};
refreshFunc();
</script>
One big problem with using confirm in this case is you cannot program it to reject. You would have to implement you own modal/dialog box so you can auto reject in 10 seconds.
Try using setInterval():
var time;
$(function() {
time = $('#time');
$('#reset').on('click', reset);
start();
});
var timer, left;
var start = function() {
left = +(time.text()); //parsing
timer = setInterval(function() {
if (0 <= left) {
time.text(left--);
} else {
clearInterval(timer);
location.replace(location);
}
}, 1000);
};
var reset = function() {
if (timer) {
clearInterval(timer);
}
time.text('59');
start();
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h1><span id='time'>59</span> second(s) left</h1>
<input id='reset' value='Reset' type='button' />

invoke function everytime a boolean becomes false in JavaScript

I'm trying to invoke a function everytime the "paused" property of a html audio element gets false.
I have a timer which shall count the time a audiofile is actually listened to (i also want to exclude the time while searching with the time bar).
I tried it with SetInterval checking all the time for the status of "paused". Unfortunately this isn't working accurately and quite often misses the status change and so lets the time counter count on.
Is there a simple way to invoke a function everytime a boolean changes?
Help would be very appreciated.
Thanks, f.
Thanks for you answer. Unfortunately this didn't do the trick.
Here's the Code:
<html>
<head>
</head>
<body>
<h5 id="test">Audio Timer</h5>
<audio id="player" src="kerry.wav" controls></audio>
<form name="d">
<input type="text" size="8" name="d2">
<h1 id="time"></h1>
</form>
<script>
var audio = document.getElementById("player");
var millisec = 0;
var seconds = 0;
var timer;
function display() {
if (millisec >= 99) {
millisec = 0
seconds += 1
} else
millisec += 1
document.d.d2.value = seconds + "." + millisec;
timer = setTimeout("display()", 10);
}
function starttimer() {
if (timer > 0) {
return;
}
display();
}
function stoptimer() {
clearTimeout(timer);
timer = 0;
}
function startstoptimer() {
if (timer > 0) {
clearTimeout(timer);
timer = 0;
} else {
display();
}
}
function resettimer() {
stoptimer();
millisec = 0;
seconds = 0;
}
setInterval(function () {
var time = audio.paused;
if (time == false) {
startstoptimer();
}
}, 1);
</script>
</body>
</html>
Unfortunately the SetInterval(function().. isn't fast enough to track the audio.paused. which seems is what i need. As you can see this code always does start the timer, but quite often it doesn't stop it when you press pause or when you use the time bar to seek through the audio.
Any idea how to accomplish that?
Create a variable that calls your audio tag
var yourAudio = document.getElementById("audio")
And then
yourAudio.onpause=YourFunction()
If that is not what you are looking for, post your code or part of it, give us more information.
With a while (true) my page didn't even load. But I finally brought it to life by adding two event listeners listening to "playing" and "pause" which invoke the startstoptimer function.
audio.addEventListener("playing", startstoptimer);
audio.addEventListener("pause", startstoptimer);
those two lines were all it needed :)
thanks.

Start and Stop timer not working

I am trying to make a timer that starts when you click the top button and stops and resets when you click the bottom button. Here is a link to my fiddle http://www.jsfiddle.net/AbrGL/
My HTML:
<input type="submit" id="start-clock" value="Click here to start timer" name="submit" onClick="startclock()"/>
<div id="timer">0</div>
<input type="submit" id="stop-clock" value="Click here to stop and reset the timer" name="submit" onClick="stopclock()"/>
My JavaScript:
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
}
else if (clicked === true) {
}
}
function stopWatch() {
sec+;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=0;
clicked = false;
}
Ok you have a lot of typos.
First, sec+; does not do anything. It should be sec++;.
Second, your onClick properties point to startclock() and stopclock(), which should actually be startClock() and stopClock(). Function names are case-sensitive in JavaScript.
Third, the clicked variable is undefined so startClock() will never actually do anything. Add var clicked = false; before your function declarations.
Last but not least, sec is undefined, so incrementing it doesn't make sense. Add var sec = 0; before your function declarations.
HTML should look like
<input type="submit" id="start-clock" value="Click here to start timer" name="submit" onClick="startClock()"/>
<div id="timer">0</div>
<input type="submit" id="stop-clock" value="Click here to stop and reset the timer" name="submit" onClick="stopClock()"/>
and JavaScript should look like
var clicked = false;
var sec = 0;
function startClock() {
if (clicked === false) {
clock = setInterval("stopWatch()", 1000);
clicked = true;
}
else if (clicked === true) {
}
}
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
function stopClock() {
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=0;
clicked = false;
}
Here is a working fiddle with the changes above: http://jsfiddle.net/AbrGL/8/
In the "stopWatch()" method, Replace sec+; with sec++;
I also found some typos, JavaScript is a CaSe SeNsitIvE language
I've made a few changes dom and js
HTML
<input type="button" id="start-clock" value="Click here to start timer"/>
<div id="timer">0</div>
<input type="button" id="stop-clock" value="Click here to stop and reset the timer"/>
JS
var clock;
var sec = 0;
document.getElementById("start-clock").addEventListener("click",function(){
clock = setInterval(stopWatch,1000);
},false);
function stopWatch() {
sec++;
document.getElementById("timer").innerHTML = sec;
}
document.getElementById("stop-clock").addEventListener("click",function(){
window.clearInterval(clock);
sec = 0;
document.getElementById("timer").innerHTML=sec;
},false);
and have a look at jsFiddle
Try this one :
http://tutorialzine.com/2015/04/material-design-stopwatch-alarm-and-timer/
this is the best i have ever used, you can make little changes accordingly if required.

Categories

Resources