JavaScript with Timeout Function - javascript

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.

Related

way too keep function that called by event listener in execution

i try to make a button that get the time now ,put it in element and updated every one second using the event listener the problem that the time disappear immediately
var time
function updateTime(){
time = new Date().toLocaleTimeString();
document.getElementById('showtime').innerHTML=time
setInterval(updateTime, 1000);
}
document.getElementById("btnclock").addEventListener("click", updateTime);
html
<button id="btnclock"> Start Clock</button>
<p id='showtime'> </p>
Update can call setInterval(), but, as others have pointed out, we only want at most one interval timer running. This can be expressed tersely with a nullish coalescing assignment (not so tersely named).
Below, once the intervalID has been initialized, the setInterval() will no longer be evaluated. Keeping the interval id around is useful because it allows for a stop button, also demonstrated...
let intervalID;
function updateTime(run) {
document.getElementById('showtime').innerHTML = (new Date()).toString()
intervalID ??= setInterval(updateTime, 1000);
};
document
.getElementById("btnclock")
.addEventListener("click", updateTime);
document
.getElementById("btnclock-stop")
.addEventListener("click", () => {
clearInterval(intervalID)
intervalID = null; // so the setInterval assignment can run
});
<button id="btnclock"> Start</button>
<p id='showtime'>&nbsp</p>
<br/>
<button id="btnclock-stop"> Stop</button>
The issue is that when you click the button, updateTime function calls setInterval(updateTime, 1000) which creates a timer. The timer calls updateTime function every second. But updateTime creates another timer while the first one is still running. So in fact what is happening is that every second every running timer creates a new timer so after 10 seconds you will have 1024 timers running at the same time. This is obviously not what you want.
Try something like this:
var timer = 0;
function startTimer() {
if (!timer) {
timer = setInterval(updateTime, 1000);
}
}
function stopTimer() {
clearInterval(timer);
timer = 0;
}
function updateTime() {
var time = new Date().toLocaleTimeString();
document.getElementById("show-time").innerHTML = time;
}
document.getElementById("start-clock").addEventListener("click", startTimer);
document.getElementById("stop-clock").addEventListener("click", stopTimer);
<button id="start-clock">Start Clock</button>
<button id="stop-clock">Stop Clock</button>
<p id="show-time"></p>
It is important to destroy the timer when you no longer need it. Function clearInterval does it.

Javascript or Jquery function with timer that resets each time it is called

I am looking for a way to call a function that should wait for 1000 miliseconds before executing. And when the function is called again before the 1000 miliseconds are reached, the timer should restart. So that the function runs 1000 miliseconds after the last time it was called.
So let's say I have a button:
<button type="button" id="btnclick">Click Me!</button>
And I want to display an alert after exactly 1000 miliseconds after the last time it was clicked. But when the button is clicked a second time, before the 1000 miliseconds have past, then the timer should restart.
If someone clicks the button 1 time, then the alert displays 1 second after the click.
If someone clicks the button, and then clicks again after 999 miliseconds, and then again after again 999 miliseconds, then I want to run the function 1 second after the last click (so 2,98 seconds after the first click).
Is this possible? And how?
My Best guess would be something like:
function delay(callback, ms) {
var timer = 0;
return function () {
var context = this, args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
callback.apply(context, args);
}, ms || 0);
};
}
$('#btnclick').click(function(e){
console.log('I want to see this everytime the button is clicked, without any delay');
delay(waitFunction(),1000);
});
function waitFunction(){
console.log('I want to see this 1 second after the LAST click');
}
(inspiration from: Wait for function till user stops typing )
Yes it is possible. you just have to check if an timeout is already counting down and, if it is, reset it. Here is a simple example.
// set timer-variable
var timer = null;
//on button-click
$('#btnclick').click (function (e) {
//clear timeout if already applied
if (timer) {
clearTimeout (timer);
timer = null;
}
//set new timeout
timer = setTimeout (function () {
//call wait-function and clear timeout
waitFunction ();
clearTimeout (timer);
timer = null;
}, 1000);
});
function waitFunction () {
console.log ('I want to see this 1 second after the LAST click');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" id="btnclick">Click Me!</button>
I used lastclick variable to store date user clicked.
I defined lastclickworked variable to avoid double setTimeout calls. In settimeout function, i checked if 1 second passed, run the code. if 1 second doesn't passed then call settimeout again with 1 seconds- passed time
var lastclick=null;
var lastclickworked=true;
function clickMe(){
lastclick=new Date();
if(lastclickworked)
runcallback(1000);
}
function runcallback(milliseconds){
lastclickworked=false;
setTimeout(function(){
var current = new Date();
var milliseconds = (current.getTime() - lastclick.getTime());
if(milliseconds<1000){
runcallback(1000-milliseconds);
}else{
lastclickworked=true;
console.log('you clicked 1 second ago');
}
},milliseconds);
}
<button onclick="clickMe();">Click Me!</button>

Why does the countBreak() function keep updating and not the countdown() function in JavaScript?

I want the two functions of my timer to keep running one after the other, the countdown() function runs once and the countBreak() function continually runs, would you be kind to explain why it's happening that way and how to work it out and how to pause the 'sessionCount div' when clicked? This just the part of the code that I have challenge with.
var timeCount; // to hold the timer
function countdown() {
var sessionData = countSession.textContent;
sessionData--;
document.getElementById('sessionCount').innerHTML = sessionData; //updating the content of session count
timeCount = setTimeout('countdown()', 1000); //to start the timer
if (sessionData < 0) {
clearTimeout(timeCount);
countBreak();
}
}
//function to countdown breaklength
function countBreak() {
var breakCount = breakDisplay.textContent;
document.getElementById('sessionCount').innerHTML = breakCount; //updating the content of session count
breakCount--;
timeCount = setTimeout('countdown()', 1000); //to start the timer
if (breakCount < 0) {
clearTimeout(timeCount);
countdown();
}
}
//add eventListening to the div sessionCount
countSession.addEventListener('click', countdown, false);
<div id='displayBreak'></div>
<button type='button' id='minusButton'>minus</button>
<!--decreases the stored variable-->
<button type='button' id='plusButton'>plus</button>
<!--increses the stored variable-->
<div id='displaySession'></div>
<button type='button' id='minusSession'>minus</button>
<!--decreases the stored variable-->
<button type='button' id='plusSession'>plus</button>
<!--increses the stored variable-->
<div id='sessionCount'></div>
You should pass the function definition as the first paramenter of setTimeout, not the function call as a string.
timeCount = setTimeout(countdown, 1000);
instead of
timeCount = setTimeout('countdown()', 1000);

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' />

count the number of click in an interval of time

how can I count the number of clicks in a time interval, for instace: how many clicks the user did in 2 seconds?? I know how to count clicks but I don't know how to measeure time
Thanks
Try using a timeout to clear the function that detects the clicks. With jQuery, try this:
var clicks=0;
function myClickFunction(event){
clicks++;
}
$(function(){
$("#something").bind("click",myClickFunction);
setTimeout(function(){
$("#something").unbind("click",myClickFunction);
alert("You clicked "+clicks+" times.");
},2000);
});
Replace #something with a jQuery selector of an element you want the clicks to be detected on and the alert line with your own code that will be run after the timer has run out.
Ad#m
HTML:
<button>Click me!</button>
<div id="status">Not Running</div>
JS:
var running = false,
count = 0,
run_for = 2000;
var end_counter = function() {
if (running) {
running = false;
$("#status").text("Not Running");
alert(count);
started_at = 0;
}
};
$('button').click(function() {
if (running) {
count++;
} else {
running = true;
$("#status").text("Running");
count = 1;
setTimeout(end_counter, run_for);
}
});
Demo: http://jsfiddle.net/pXMxQ/2/
define a variable
attach click handler to element
set variable = 0
start ur timer (setTimeout)
increment variable on each click
when timeout handler excutes, detach ur handler
- OR -
define a variable for counter
define a variable for doCounting
set counter = 0, doCounting = true
start ur timer (setTimeout)
increment counter on each click if doCounting is true
set doCounting = false when timeout handler executes
Use the setTimeout function
e.g. if Every click increments a variable clickcount you could do the following:
function startCounting(){
clickcount = 0;
setTimeout(function(){alert("you made "+clickcount +" clicks!");}, 2000);
}

Categories

Resources