Is there any possibilities of capturing tick of each seconds in setTimeout. Say for a scenario I need to logout user after 5 seconds with a message displayed, say in a div, saying "You will be logged out in 5 seconds". then 4,3,2,1 and logout after timeOut
Ex:
setTimeout(function(){
$("#myDiv").text("you will be logged out in " + n + " seconds");
//"n" being tick of each second.
},5000)
I searched over internet for this but nowhere I can see the solution. Or anything that can be done with setInterval for this scenario is also good point here. Any ideas or light on this?
Well you could use the setInterval in conjunction with the clearInterval methods:
var n = 5;
var timeoutID = window.setInterval(function() {
// this callback will execute every second until we call
// the clearInterval method
$('#myDiv').text('you will be logged out in ' + n + ' seconds');
n--;
if (n === 0) {
// TODO: go ahead and really log the dude out
window.clearInterval(timeoutID);
}
}, 1000);
You can have a global variable and use that to show tick. like below
var counter = 5;
var timeInterval= setTimeout(function(){
$("#myDiv").text("you will be logged out in " + n + " seconds");
//"n" being tick of each second.
counter = counter - 1;
clearInterval(timeInterval) if(counter==0)
},1000)
Related
I made a timer going even after reloading the page using javascript's session storage.
BUT regarding the timer at the first place, I want to get it started from getting USER INPUT.
Instead of specific number of time like 300(what I did so far below), I want to get a value from the user. Like, when the user clicked on a button on the page a pop up shows up asking the user how much time you want to put for the timer and the user put the value whatever he/she wants and the timer gets started upon that.
var userTime1 = 300;
var time = sessionStorage.getItem('timer_time');
var min = sessionStorage.getItem('timer_min');
var sec = sessionStorage.getItem('timer_sec');
if (!time){
time = userTime1;
min = parseInt(time/60);
sec = time%60;
}
var interval = setInterval(function () {
time--;
min = parseInt(time/60);
sec = time%60;
sessionStorage.setItem('timer_time', time);
sessionStorage.setItem('timer_min', min);
sessionStorage.setItem('timer_sec', sec);
document.getElementById("timeLeft1").innerHTML = min + "min" + sec + "sec";
};
if (time == 0) {
clearInterval(interval);
sessionStorage.removeItem('timer_time');
sessionStorage.removeItem('timer_min');
sessionStorage.removeItem('timer_sec');
sessionStorage.clear();
alert("Timer Expired!");
}
}, 1000);
In an agenda/calendar app I'm working on, I display a line to indicate the current time. I want to update the position of this line every minute.
If I start a setInterval function when the calendar component did mount or will mount, there is a change that it starts at the 59th second (or just not the 1st second) and the time will always be different from the time that the device is showing (computer, smartphone, ...).
But I would like that both times are matching. So I was wondering if it is possible to start the interval when a new minute starts of if there is another way to get a time update.
EDIT: Current code
componentDidMount() {
setInterval(() => {
this.setState({ currentTime: new Date() })
}, 60 * 1000);
}
You can get fairly close, by calculating the number of seconds until the next minute, and performing a timeout on the difference.
(function showTime(){
console.log('update time');
var time = document.getElementById('time');
var now = new Date();
time.innerHTML = `${now.getHours()}:${now.getMinutes()}`;
setTimeout(showTime, (60 - now.getSeconds()) * 1000);
})();
<div id="time"></div>
Use SetTimeout to call a function that repairs any deviation for each iteration and relaunches with a new call to setTimout.
function repairAndRelaunch (cnt) {
// capture current secs
var secs = (new Date()).getSeconds();
// relaunch with corrected seconds - limit iterations for testing
if (5 > cnt++) setTimeout('repairAndRelaunch(' + cnt + ')', (60-secs)*1000);
// log to observe discrepencies
console.log('for cnt = ' + cnt + ', secs = ' + secs);
};
// test control flow
window.onload = function() {repairAndRelaunch(0);};
I am making an AJAX call in my code. What i want is to hit the AJAX call at 20th second of every minute. This is the AJAX request that i am making.
setInterval(function(){
$.ajax({
url: url,
headers: { 'x-cyclops-ajax': 'yes' },
method: 'POST',
dataType: 'json',
success: function(data) {
var chart = $('#container').highcharts();
var keys = Object.keys(data["histData"]);
$( "#main-div" ).empty();
for( var i=0; i< keys.length; i++) {
chart.series[i].setData(data["histData"][keys[i]]["histFailure"], true);
$('#main-div').append( '<div class="homepage-availability-inner-div"><h1 class="homepage-availability-text"> ' + keys[i] + ': <span class="dashboard-success">' + data["availData"][keys[i]] + ' </span> </h1></div>');
}
chart.xAxis[0].setCategories(data["histKeys"]);
console.log("Data:" + JSON.stringify(data["availData"]));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Did not hit the AJAX call");
}
});
}, 5000);
Any help would be appreciated.
If you mean only on the 20th second as in 13:00:20, 13:01:20 , 13:02:20, ...
you would have to do something like this:
// the interval can be set lower depending on the use case, to be more accurate
// Warning a too low interval setting might kill the performance of the browser/client,
// and execute the ajax multiple times, if the milliseconds are not considerate
let interval = 1000;
// the function is called (about) every second,
// so approximately 60 times per minute and executes the ajax call only once.
setInterval(
function(){
let now = new Date();
// should only fire, if it is the 20th Second in the current minute
if(now.getSeconds() === 20){
//ajax call
console.info(now);
}
}, interval
);
The Code check every Second, if it is the 20th Second. The performance might be a bit heavy for the client, doing some many calls, but it works.
Just to think about:
It could be optimized with changing the inertval, after a hit or higher interval length, or using setTimeout instead, and calculating, the next time to call it self.
btw.:
If you want to get the milliseconds also, you would have to put the interval lower and also query the getMilliseconds() function of the now Variable, but this would probably kill the performance of the client.
here is the link to the relevant Reference to the Date function getSeconds
here is a explanation on how/why the timeout/interval is not accurate, but there are also other reasons.
Optional (just4fun):
If you want do less setInterval calls, you could use setTimeout and call the function recursively, the "problem" being, how to tweak the time setting to get close to the 20th seconds without missing it.
Here is a small basic example, to start from:
(Yes the code isn't very optimized, and could be better structured, but I hope it gives a rough idea)
// the 20th Second, when the ajax call should execute
const selectedSecond = 20;
// can be tweaked to hit closer to 20th Second (ms)
let shortInterval = 400;
// depence on the size less calls are made
let safetyBuffer = 2;
// helper Variable, 60 Seconds
let sixtySeconds = 60;
// timeout value which is set dynamic, first time will execute "immediately"
let currentTimeout = 0;
function timeoutHandler(){
// gets current Time
let now = new Date();
let seconds = now.getSeconds();
if(seconds === selectedSecond){
// **** here the ajax call should go ****
console.info("ajax Called!!");
// sets the next timeout 58s later, not to miss the 20th Second
currentTimeout = (sixtySeconds - safetyBuffer) * 1000;
}else if(seconds > selectedSecond){
// sets the next timeout to 2s beforethe 20th Second
currentTimeout = (sixtySeconds - safetyBuffer - seconds + selectedSecond) * 1000;
} else if(seconds < selectedSecond - safetyBuffer) {
// sets the next timeout to 2s beforethe 20th Second
currentTimeout = (selectedSecond - safetyBuffer - seconds) * 1000;
} else {
// sets the next timeout to shortInterval(=400ms),
// for the last 2s, it will be more often, to not miss the 20th second
currentTimeout = shortInterval;
}
// calls the function with the new optimized timeout
setTimeout(timeoutHandler, currentTimeout);
}
// initial call
setTimeout(timeoutHandler, currentTimeout);
You can use setInterval method for continuous loop and when current second is 20 you can make ajax call. Please see the code snippet:
setInterval(function() {
if(new Date().getSeconds() === 20) {
// Your ajax call
}
}, 1000);
I want to run a timer in JavaScript for 30 seconds, play a beeping .WAV file, then count 10 seconds and play the beep again. I want this to repeat until either a desired time is hit or the user intervenes and clicks a stop button.
This is how I've implemented it:
function startWorkOut(param) {
if (param === 1) {
setTimeout(playBeep, 30000); //30 second workout
}
else if (param === 0) {
setTimeout(playBeep, 10000); //10 second rest
}
return;
}
function playBeep() {
beep.play(); //already loaded above this snippet
i++; //simple switch for going back and forth between 30 & 10 secs
if (i % 2 === 1) {
startWorkOut(0);
}
else startWorkOut(1);
return;
}
The problem is I don't know how to stop it. Because these two functions are calling each other back and forth, I need to know how to put in some sort of a manual break.
Assign it to a variable
var beepTimer = setTimeout(playBeep, 30000); //30 second workout
clearTimeout(beepTimer); // This will clear that timer
Try this;
var timerConst;
function startWorkOut(param) {
if (param === 1) {
timerConst = setTimeout(playBeep, 30000); //30 second workout
}
else if (param === 0) {
timerConst = setTimeout(playBeep, 10000); //10 second rest
}
return;
}
function playBeep() {
beep.play(); //already loaded above this snippet
i++; //simple switch for going back and forth between 30 & 10 secs
if (i % 2 === 1) {
startWorkOut(0);
}
else startWorkOut(1);
return;
}
function stop(){
clearTimeout(timerConst);
}
Store the reference returned by setTimeout or setInterval method and then use window.clearTimeout or window.clearInterval to remove those timers. Example:
var ref1 = window.setTimeout(function() {your code}, 5000);
var ref2 = window.setInterval(function() {your code}, 5000);
An then remove them using the following code:
window.clearTimeout(ref1);
window.clearInterval(ref2);
Hope it help.
jsFiddle Demo
"I want to run a timer in JavaScript for 30 seconds, play a beeping .WAV file, then count 10 seconds and play the beep again. I want this to repeat until either a desired time is hit or the user intervenes and clicks a stop button."
Timers are 3 and 1 second for brevity
var playing;//variable for timer
function startWorkOut(){
var entry = playing === void 0;//true if playing is undefined
var interval = entry? 3000 : 1000;//first entry is 3s timer, others are 1s
if(!entry)playBeep();//play a beep except when the workout timer is first started
playing = setTimeout(startWorkOut,interval);//play a beep in either 3s or 1s
}
function stopWorkOut(){
clearTimeout(playing);//stops timer
playing = undefined;//restores variable state
}
I seem to be having some unexpected results with a framerate counter in javascript. Up until recently the counter has been fine and I have been running my little js app at 30fps.
It uses setTimeout() (with a time adjustment to counter the system 'falling behind').
window.requestAnimFrame = (function()
{
return function (callback) {
time += FPS;
Heartbeat._eTime = (new Date().getTime() - Heartbeat._start);
var diff = Heartbeat._eTime - time;
Heartbeat._delta = FPS - diff;
Heartbeat._deltaS = Heartbeat._delta / 1000;
window.setTimeout(callback, FPS - diff);
};
})();
Heartbeat is merely an object that contains the frame rate info.
*Here is my problem: *
_MainLoopHandler: function () {
timer = new Date().getTime();
counter = timer;
while (this._messages.length > 0 && (counter - timer) < 5)
{
// process messages from _messages array
}
counter = new Date().getTime();
// THE ABOVE IS HAPPY AT 30 FPS
while ((counter - timer) < 6) {
1 + 1;
}
// THE ABOVE WHILE IS VERY UNHAPPY :(
}
So the above code block is the function that is called from setTimeout every 33.33 milliseconds (30 fps). if I take the bottom while loop out, the FPS counter will sit happily at 30fps. However, if I leave it in, the FPS counter goes crazy. it goes up to the 200FPS 300FPS then suddenly goes -200FPS -10FPS 0.01FPS. Its completely off the wall. The while loop will only run maybe 10 times per "frame".
Note also, the hard-coded values 5 and 6 are simply a check to see if 5 or 6 milliseconds have passed while processing the loops (for load balance).
Is this simply javascript being unable to handle the amount of info or has anyone else had a similar problem.
Thanks!
I don't really know what's going on, but I think you should use local variables to control your time, constantly reassess counter and process 1 message at a time. Also, I don't really understand that last loop (I've also renamed the variables):
_MainLoopHandler: function () {
var start = new Date().getTime();
var current;
do {
if (this._messages.length === 0) break;
// process 1 message
current = new Date().getTime();
} while (current - start < 5);
}
You can also encapsulate the timing concern in an object (not shown) to streamline the code:
_MainLoopHandler: function () {
var timing = new Timing();
do {
if (this._messages.length === 0) break;
// process 1 message
} while (timing.elapsed() < 5);
}