I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
Related
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
I can see there are a couple of similar questions asked here but unfortunately I couldn't find the answer I expect.
I am quite new to Programming and trying my hands on Javascript Progress Bar. I have a counter to countdown whenever the progress bar runs out of width but i got the problem, when the tab in focus is inactive, the progress bar pauses thereby keeping counter not to countdown.
I got the idea of using web workers http://www.tutorialspoint.com/html5/html5_web_workers.htm but I couldn't get that to work. I would appreciate any form of help I get here.
Below is my Code.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/
jquery.min.js">
</script>
<style>
#progressContainer {
position: relative;
width: 97%;
height: 25px;
background-color: #ddd;
margin-bottom: 15px;
}
#progressBar {
position: absolute;
width: 0%;
height: 100%;
background-color: #A9A9A9;
}
#container{
width: 200px;
height: 200px;
border: 1px solid black;
padding: 10px
}
</style>
<script>
$(document).ready(function(){
$("#countDownBtn").click(function(){
var cdNumber = $("#countDownId").val();
var id = setInterval(frame, 100);
var elem = document.getElementById("progressBar");
var progressBarWidth = 101;
function frame() {
if (progressBarWidth === 0) {
clearInterval(id);
cdNumber--;
$("#countDownId").val(cdNumber);
console.log(cdNumber);
if (cdNumber === 0) {
clearInterval(id);
}
else {
elem.style.width = '100%';
progressBarWidth = 100;
//alert("Hi");
}
}
else {
progressBarWidth--;
elem.style.width = progressBarWidth + '%';
}
}
});
});
</script>
</head>
<body>
<div id="container">
<div>
<input type="text" id="countDownId" value="">
<button id="countDownBtn" class="btn">Click</button>
</div><br>
<div id="progressContainer">
<div id="progressBar"></div>
</div>
</div>
</body>
You'll always run into such problems when depending on the precision of some interval; even requestAnimationFrame. They ain't precise.
The better approach (not just in this case, but pretty much every time you have to transition a value over time) is to save the startTime and compute the passed time in the interval (as #Nosyara already suggested).
When dealing with scaling-factors and/or pausing of this stuff, things can get messy again. Here a utility for this task:
// The basic concept of this "Clock" is a linear equation over Date.now()
// plus the logic to make this equation pausable.
// therefore it's completely independant of **any** interval; it's just math.
function Clock(v){
var p=true,m=1,b=+v||0,n=Clock.now;
return Object.assign(Object.create(Clock.prototype),{
// getter() / setter(value)
// I don't use real getter and setter, because this syntax
// allows/implements method-chaining
value(v){return arguments.length?(b=(+v||0)-(!p&&m*n()),this):b+(!p&&m*n())},
speed(v){return arguments.length?(v=+v||0,p||v===m||(b+=n()*(m-v)),m=v,this):m},
paused(v){return arguments.length?(((v=!!v)===p)||(b+=n()*((p=v)?m:-m)),this):p},
});
}
Object.assign(Clock.prototype,{
valueOf(){return this.value()},
//aliases for setting the paused() state; doesn't matter if you call them repeatedly.
start(){return this.paused(false)},
stop(){return this.paused(true)},
});
Clock.now=Date.now; //the function used for timing
//Clock.now=performance&&performance.now?performance.now.bind(performance):Date.now;
Now to your code:
$(function(){
function frame(){
//yes, countDown get's converted to Number
var value = Math.max(0, countDown);
var count = Math.ceil(value);
var progress = value % 1;
$progressBar.width( progress * 100 + "%" );
//so that I don't update $countDown.val() on every frame, but only if necessary
//on the other hand, it wouldn't be that bad.
if(count !== lastCount) $countDown.val( lastCount = count );
//either stop the countDown or request the next frame.
if(value > 0) requestAnimationFrame(frame);
else countDown.stop();
}
//create a Clock and set speed. Clock is paused by default.
var countDown = Clock().speed( -1 / 10000/*ms*/ );
var $progressBar = $("#progressBar");
var $countDown = $("#countDownId");
var lastCount;
$("#countDownBtn").click(function(){
//if !countDown.paused() then there already is a pending `requestAnimationFrame(frame)`
//from the last call of frame()
if(countDown.paused()) requestAnimationFrame(frame);
countDown.value( $countDown.val() ).start();
});
})
I had similar problems in one of my projects in Chrome browser. The root of problem, that Chrome allows up to 1 timer event per second (setTimeout or setInterval) if tab is not active. In case there more than 1 call per second - it creates queue, than behavior of page depends on logic inside events and may look not as expected. One of solutions is to check visibility of the page and manage intervals Check here
As #ManoDestra pointed out in the comment, you should use requestAnimationFrame instead of setInterval.
The best solution I would propose is utilizing the HTML5 Visibility API to detect when a tab becomes active again after being inactive, and then update the progress bar accordingly. Perhaps you could store the timestamp of the countdown when it is initialized, and when the tab becomes active again, you look at the new timestamp and make a comparison.
You can use setTimeout instead and use recursion. It could look something like this:
var stopInterval = false;
frame();
function frame() {
if(stopInterval) return;
// Your stuff to run in interval HERE
setTimeout(frame, 100);
}
Webworkers are not supported in older browsers. Also browsers specify how they handle setTimeout and setInterval on inactive tab individually, so the behavior may differ. Chrome seems to slow down the recursion alot (1 per second?).
Specifically in your case you can use clock time to represent right progress. When you don't want trust browser about interval events.
Let say you want 10 sec countdown:
var tm = new Date().getTime() + 10000; // 10 sec in milliseconds
setInterval(function(){
var secondsPassed = (tm - new Date().getTime()) / 1000;
// update UI
}, 100); // You can use variable here in different visibility modes
I'm trying to make a jQuery function that spells my name out letter by letter. My name is Jake, so I want it to start out with nothing, then it'll display a J, then Ja, then Jak, then Jake. Let's just say that I'm modifying a paragraph element with class name:
<p class=Name> *name gets 'typed' here* </p>
I've tried using the .delay() function and the setTimeout() function, but I'm new to jQuery so I'm probably using them wrong.
$(document).ready(function()
{
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 500);
setTimeout(function(){$(".name").text('Jak');}, 500);
setTimeout(function(){$(".name").text('Jake');}, 500);
});
Here is a jfiddle of my most recent attempt:
http://jsfiddle.net/pg7Cu/
This just delays for 500 milliseconds then types my name all at once. I'm trying to get it to type one letter every 500 milliseconds. Can someone help me figure out how to do this?
Simply use a recursive function:
var name = "Jake";
function typeName(name, iteration) {
// Prevent our code executing if there are no letters left
if (iteration === name.length)
return;
setTimeout(function() {
// Set the name to the current text + the next character
// whilst incrementing the iteration variable
$('.name').text( $('.name').text() + name[iteration++] );
// Re-trigger our function
typeName(name, iteration);
}, 500);
}
// Call the function to begin the typing process
typeName(name, 0);
JSFiddle demo.
We can extend this slightly to remove the need for initially passing in the iteration variable by adding this as the first line in our typeName function:
var iteration = iteration || 0;
Now you can simply call:
typeName("My name here");
JSFiddle demo.
Actually You can do it also with css only, No need of javascript/jQuery.
HTML
<p class="text">Jack.</p>
CSS
.text
{
width: 30em;
white-space:nowrap;
overflow:hidden;
-webkit-animation: type 5s steps(50, end);
animation: type 5s steps(50, end);
}
#keyframes type{
from { width: 0; }
}
#-webkit-keyframes type{
from { width: 0; }
}
Demo
Here is a simple one:
http://jsfiddle.net/pg7Cu/7/
var text = "Hello what's up?";
function letter() {
var oldt = $(".name").text(); // grab old text
var t = text.charAt(0); // grab first text's letter
text = text.substr(1); // shorten the text
$(".name").text(oldt + t); // show old text + the one letter
// if there's anything left to type, continue.
if(text.length > 0) setTimeout(letter, 100);
}
$(document).ready(function()
{
setTimeout(letter, 100);
});
It sets a timeout for a letter, and when the letter is shown, if there is more, it sets the timeout again. Sort of recursion.
You're close. Start by incrementing the timeouts; as the timer starts running immediately:
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 1000);
// etc
And don't set the differences in time exactly the same (as people don't hit a key every x ms constantly)
Check out a revised version: http://jsfiddle.net/pg7Cu/1/
And you could create more beautiful code etc. etc. but this works.
EDIT
Ok I took the challenge ;) Check out this Fiddle. You can call the function simulateTyping() with your own string, and at random intervals it will append the next character, until the whole string is on the screen. You could even create a plugin from it (by NOT hard-coding the element the text should be appended to).
function simulateTyping(myString, currentChar) {
var delay = Math.floor(Math.random()*(250-50+1)+50); // random between 50 and 250 milliseconds
currentChar = currentChar || 0;
setTimeout(function() {
$('.name').append(myString.charAt(currentChar))
if(++currentChar < myString.length) {
simulateTyping(myString, currentChar);
}
}, delay);
}
You can try with different timeouts:
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 1000);
setTimeout(function(){$(".name").text('Jak');}, 1500);
setTimeout(function(){$(".name").text('Jake');}, 2000);
I'm working on a auto logout using setTimeout and clearTimeout. Should be really straight forward but the clear timeout doesn't seem to stop the timeout and the function is called anyway. I have it set up that the session variable populates a text input that the javascript then reads and compares to the time now. if the difference is more than or equal to 20 seconds an overlay div shows giving an option to renew the session or it will logout in 10 seconds. The script that check the last activity auto runs every ten seconds. Obviously once I've got it working the timings will be longer - these are just for testing purposes.
I have trawled the web but can't seem to find an obvious solution as it not so complicated and looks like it really should just work!
Here's my code:
var t = 0;
function check_status(){
var time_now = Math.floor(new Date().getTime() / 1000);
var last_activity = document.getElementById("last_activity").value;
var since_last_activity = time_now-last_activity;
console.info(since_last_activity);
if(since_last_activity >= 20){
// show div
document.getElementById("logout_warning").style.height = document.documentElement.clientHeight+"px";
document.getElementById("logout_warning").style.display = 'block';
// start countdown
var t = setTimeout("logout();", 10000);
}
}
function logout(){
document.getElementById("logout_warning").style.display = 'none';
location.href="/user/logout";
}
function renew(){
clearTimeout(t);
var time_now = Math.floor(new Date().getTime() / 1000);
document.getElementById("last_activity").value = time_now;
document.getElementById("logout_warning").style.display = 'none';
}
setInterval('check_status()', 10000);
and then in the body...
<div id="logout_warning" style="display:none; width:100%; height:500px; top:0px; left:0px; position:absolute; background-image:url('/images/overlay.png'); z-index:100000;">
<div style="width:300px; position:relative; margin:200px auto; border:1px solid #000000; background-color:#FFFFFF; padding:10px; text-align:center;">
You're going to be logged out in 10 seconds! oh no!<br/><br/>
<button type="button" onclick="renew();">Click here</button> to renew your session
</div>
</div>
The last activity variable is pulled from a text input that is populated by a session variable. This bit seems to work, as in when you click the renew button the value of the input is changed and the console output shows that the time since last activity has been reset.
I hope this makes sense. Please ask for clarification but I'm really stumped on this one!
Thanks!
You have two ts.
var t = 0;
This one in the outside scope.
var t = setTimeout("logout();", 10000);
This one in the inside scope.
clearTimeout(t);
This is reading the one on the outside scope.
Remove the var from the one on the inside scope.
That's because you're redefining the variable in the function and it becomes local to that function, the global t is still 0:
var t = setTimeout("logout();", 10000);
remove the var before the variable!
You're overshadowing the global variable t with a local one:
var t = 0;
function check_status() {
var t = setTimeout("logout();", 10000);
// ^^^^
}
function renew() {
clearTimeout(t);
}
Remove the var to make t refer to the global variable.