Clear timeout of a functions inside global function - javascript

I have set a function that loads on document ready with name myFunction. There are 5 functions inside it with different timeouts. I want to clearTimeout of 3rd and 4th functions on clicking a button inside my html code with id #btn . Here is my code
<doctype! HTML>
<html>
<head>
<title>
My Page
</title>
<script src="jquery-3.2.1.js">
<script src="myScript.js">
<script type="text/javascript">
$(document).ready(myFunction);
</script>
</head>
<body>
<button id="btn">
</body>
</html>
myScript.js is below
function myFunction(){
setTimeout(function function1(){
// do stuffs
}, 5000);
setTimeout(function function2(){
// do stuffs
}, 10000);
setTimeout(function function3(){
// do stuffs
}, 15000);
setTimeout(function function4(){
// do stuffs
}, 20000);
setTimeout(function function5(){
// do stuffs
}, 25000);
}

To clear a timeout, you must assign it to a variable which holds the reference. Here is an example:
var t1,t2,t3,t4,t5;
function myFunction(){
t1 = setTimeout(function function1(){
// do stuffs
}, 5000);
t2 = setTimeout(function function2(){
// do stuffs
}, 10000);
t3 = setTimeout(function function3(){
// do stuffs
}, 15000);
t4 = setTimeout(function function4(){
// do stuffs
}, 20000);
t5 = setTimeout(function function5(){
// do stuffs
}, 25000);
}
function myClearFunction(){
clearTimeout(t3);
clearTimeout(t4);
}
Call myClearFunction() from your button to clear the third and forth timers.

You can use clearTimeout for this. Here's a functional demo:
var timer1 = setTimeout(function() {
console.log('timer1');
}, 5000);
var timer2 = setTimeout(function() {
console.log('timer2');
}, 10000);
var timer3 = setTimeout(function() {
console.log('timer3');
}, 15000);
var timer4 = setTimeout(function() {
console.log('timer4');
}, 20000);
var timer5 = setTimeout(function() {
console.log('timer5');
}, 25000);
document.getElementById('x').addEventListener('click', function() {
clearTimeout(timer3);
clearTimeout(timer4);
});
<button id="x">Stop Timer 3 and 4</button>

SetTimeout returns a value, save that for timer 3 and 4 and then on click button click cancel those. Make sure to check if the values for 3-4 are defined before calling clear on them.
Return Value: A Number, representing the ID value of the timer that is set. Use this value with the clearTimeout() method to cancel the timer
from https://www.w3schools.com/jsref/met_win_settimeout.asp

Related

Disable timer within setInterval function with dynamic parameters

I wanted to pass dynamic parameters into a setInterval function (see question here) and specifically #tvanfosson's comment.
But now, I also want to disable that timer if a certain condition is met. I tried to define the timer variable as a global variable but I still get the timer as a undefined on this line:
console.log('else. timer=' + timer);:
else. timer=undefined
<script language="javascript" type="text/javascript">
var timer;
var params={};
params.color='light';
$(document).ready(function () {
timer=createInterval(showSmallWidget, params.color, 500);
});
function createInterval(f, dynamicParameter, interval) {
setInterval(function () {
f(dynamicParameter);
}, interval);
}
function showSmallWidget(color) {
if ($('#widget').html() == '') {
//do stuff
}
else {
console.log('else. timer=' + timer);
if (timer) { console.log('CLEAR TIMER'); timer.clearInterval(); timer = null; }
}
}
</script>
I tried to create a JSFiddle, but I can't get it to work properly: https://jsfiddle.net/puhw3z2k/
There are a couple problems:
1) You have to return the timerID from your createInterval() function:
function createInterval(f, dynamicParameter, interval) {
return setInterval(function () {
f(dynamicParameter);
}, interval);
}
2) clearInterval() works like this clearInterval(timer), not timer.clearInterval().

How can I stop custom jQuery function which is running?

I have a custom jQuery function. When it runs every 5 seconds.
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 5000);
}
return this;
};
})(jQuery);
$("#container").mycustomfunction();
I have a
clearInterval(interval);
to stop, but I also want to stop the function completely. How can I do that ?
Functions you add to this object will be attached to your object and Simple and naive solution will follow:
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 1000);
this.stop= function(){
clearInterval(interval);
}
// another function
this.alert = function(msg){
alert(msg)
}
return this;
};
})(jQuery);
to stop use
var feature = $("#container").mycustomfunction();
feature.stop();

How to make clearTimeout() happen within setTimeout()?

I have a setTimeout function already running to make a watch work, but I want to clearTimeout on this already running function when I clock on a button, but only after a few seconds. So ideally, I want a clearTimeout() inside another setTimeout() function, but I can't seem to get it working.
I have this code at the moment:
alarm.click(function() {
water.animate(anim);
setTimeout(function () { clearTimeout(time); }, 3000);
});
var time = setTimeout(function(){ startTime() },1000);
But it does it clears it straight away rather than after 3 seconds. What can I do to make it clear after 3 seconds?
edited my code, still not working :(.
You can try:
var time = setTimeout(function(){startTime(time)},1000);
And in startTime you clear time
function startTime(time) {
cleartTimeout(time);
...
}
You are calling it straight away, but you need a callback.
setTimeout(function () { clearTimeout(time); }, 3000);
function startTime() {
document.getElementById('out').innerHTML += 'starttime<br>';
}
function set() {
document.getElementById('out').innerHTML += 'set<br>';
setTimeout(function () {
document.getElementById('out').innerHTML += 'clear3000<br>';
clearTimeout(time);
}, 3000);
}
var time = setTimeout(function () {
document.getElementById('out').innerHTML += 'clear1000<br>';
startTime();
}, 1000);
set();
<div id="out"></div>

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

How to perform an action every couple of seconds?

Can someone quickly and simply explain to me how to perform an action every couple of seconds using
var timeOut = setTimeout(FunctionName, 5000);
I want to run a function every 5 seconds.
As you asked for a method using setTimeout:
function doStuff() {
console.log("hello!");
setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);
But it would probably be better to use setInterval:
function doStuff() {
console.log("hello!");
}
setInterval(doStuff, 5000);
Just put setTimeout at the end inside your function, with a call to itself - like a delayed tail-recursion.
Use setInterval:
var timeOut = setInterval(nextNotice, 5000);
var myFunction = function() {
//Do stuff
AnotherFunction();
};
var timeOut = setInterval(myFunction, 2000);
you can do something like:
$(document).ready(function ()
{
setTimeout(nextNotice, 5000);
}
function nextNotice()
{
// do stuff
setTimeout(nextNotice, 5000);
}
In the example below, when a button is clicked, the input field will start to count (for ever), starting at 0.
<html>
<head>
<script type="text/javascript">
var c = 0;
var t;
var timer_is_on = false;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout(timedCount, 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = true;
timedCount();
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Start count!" onclick="doTimer()">
<input type="text" id="txt" />
</form>
</body>
</html>

Categories

Resources