I have the following javascript code
function RefreshElastic() {
Elastic.refresh();
}
function ShowTime() {
var Sekarang = new Date();
var Waktu = Sekarang.getDate() + "/" +
Sekarang.getMonth() + " - " +
Sekarang.getHours() + ":" +
Sekarang.getMinutes();
$("#jam").html(Waktu);
Elastic.refresh();
}
var IntervalElastic = setInterval(function () {
RefreshElastic();
}, 500);
var IntervalTime = setInterval(function () {
ShowTime();
}, 1000 * 30);
I want to have 2 intervals, each has a function to call.
The RefreshElastic called only twice.
The ShowTime always called every 30 seconds.
Why is that?
Additional note:
I changed the millis for RefreshElastic to a larger value, like 5000. And RefreshElastic never called.
Related
I have a Javascript setInterval function set up to display like a timer. I'd like to display the time that is on the timer when a "next" button is clicked so the user can see how long they've spent on a certain page. I'm unsure how to connect the setInterval with a click event. This is what I have, but it's not working.
let timerId = setInterval(function () {
document.getElementById("seconds").innerHTML = pad(++sec % 60);
document.getElementById("minutes").innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
function myFunction() {
alert document.getElementById("timerId").innerHTML = "Time passed: " + timerId);
}
This should solve your problem.
var initialTime = new Date().getTime();
var timeSpent='0:00';
var timeElement = document.getElementById("time");
timeElement.innerHTML = timeSpent;
let timerId = setInterval(function () {
var currentTime = new Date().getTime();
timeSpent = millisToMinutesAndSeconds(currentTime - initialTime)
timeElement.innerHTML = timeSpent;
}, 1000);
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}
function alertFn(){alert(timeSpent)}
document.getElementById("rightButton").addEventListener('click',alertFn);
document.getElementById("wrongButton").addEventListener('click',alertFn);
<h1 id="time"></h1>
<button id="rightButton">Right</button>
<button id="wrongButton">Wrong</button>
First of all, it would be better if you put setInterval method inside the function. After that you could give your function to an event listener as an argument.
Your code should look something like this
let timerId;
function displayTime() {
timerId = setInterval(() => {
// your code
}, 1000);
}
document.querySelector('button').addEventListener('click', displayTime)
I am trying to display two timer on a webpage with different start times.
First timer only shows for 5 seconds and then after 10 seconds I need to show timer2.
I am very new to Angular and have put together following code.
It seems to be working fine except when the settimeout is called the third time it doesn't work correctly and it starts going very fast.
Controller
// initialise variables
$scope.tickInterval = 1000; //ms
var min ='';
var sec ='';
$scope.ti = 0;
$scope.startTimer1 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer1 = min + ":" + sec;
mytimeout1 = $timeout($scope.startTimer1, $scope.tickInterval); // reset the timer
}
//start timer 1
$scope.startTimer1();
$scope.$watch('timer1',function(){
if($scope.timer1 !=undefined){
if($scope.timer1 =='00:05'){
$timeout.cancel(mytimeout1);
setInterval(function(){
$scope.startTimer2()
$scope.ti = 0;
},1000)
}
}
})
//start timer 2 after 2 mins and 20 seconds
$scope.startTimer2 = function() {
$scope.ti++;
min = (Math.floor($scope.ti/60)<10)?("0" + Math.floor($scope.ti/60)):(Math.floor($scope.ti/60));
sec = $scope.ti%60<10?("0" + $scope.ti%60):($scope.ti%60);
$scope.timer2 = min + ":" + sec;
mytimeout2 = $timeout($scope.startTimer2, $scope.tickInterval);
}
$scope.$watch('timer2',function(){
if($scope.timer2 !=undefined){
if($scope.timer2 =='00:05'){
$timeout.cancel(mytimeout2);
setInterval(function(){
$scope.startTimer1();
$scope.ti = 0;
},1000)
}
}
})
In my view I simply have
<p>{{timer1}}</p>
<p>{{timer2}}</p>
You're basically starting multiple startTimer function so it's adding up. If i understood your problem well you don't even need to have all those watchers and timeouts.
You just can use $interval this way :
$scope.Timer = $interval(function () {
++$scope.tickCount
if ($scope.tickCount <= 5) {
$scope.timer1++
} else {
$scope.timer2++
if ($scope.tickCount >= 10)
$scope.tickCount = 0;
}
}, 1000);
Working fiddle
The timer keeps getting faster every time I reset it. I'm thinking I need to use clearTimeout but am unsure about how to implement it. Here's the code:
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
setTimeout(function () {
if (timeInSeconds > 0) {
timeInSeconds -= 1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours*3600)/60);
seconds = Math.floor(timeInSeconds - hours*3600 - minutes*60);
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You have to define your setTimeout as a variable to reset it.
See Fiddle
var thisTimer; // Variable declaration.
$(function(){
sessionmin = 25;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function(){
clearTimeout(thisTimer); // Clear previous timeout
timeInSeconds = sessionmin * 60;
timeout();
});
})
function timeout(){
thisTimer = setTimeout(function () { // define a timeout into a variable
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
timeout();
}, 1000);
}
You should: use setInterval instead of setTimeout, return the interval id that setInterval generates, clear that interval before you restart it. Here is an example: https://jsfiddle.net/8n2b7x0s/
$(function(){
var sessionmin = 25;
var intervalId = null;
$("#sessionMinutes").html(sessionmin);
$("#circle").click(function() {
timeInSeconds = sessionmin * 60;
// clear the current interval so your code isn't running multiple times
clearInterval(intervalId);
// restart the timer
intervalId = run();
});
})
function run(){
return setInterval(function () {
if(timeInSeconds>0){
timeInSeconds-=1;
hours = Math.floor(timeInSeconds/3600);
minutes = Math.floor((timeInSeconds - hours)/60);
seconds = (timeInSeconds - hours*3600 - minutes*60)
$("#timer").html(hours + ":" + minutes + ":" + seconds);
}
}, 1000);
}
Can anyone give me Jquery function for Time Count Down , but work like this.
Time every 15 minutes (without stop).
When time is 0, do some Ajax update function and auto start again (Without click or refresh by myself)
The time like (TimeCountDown = TimeNow - (TimeNow+15minuts)).
I just can't find functions like this, and i don't know how to work with time.
Thanks for help.
var _TimerCount = 15;
var _Timer = setInterval(function(){
TimerCountDown();
},6000);
function TimerCountDown(){
if(_TimerCount !=0){
_TimerCount -=1;
}
else{
var currentdate = new Date();
var _DateString = currentdate.getDate() + " " + currentdate.getHours() + ":" + currentdate.getMinutes() + ":" + currentdate.getSeconds();
_TimerCount = 15;
$.get("C# CODE FILE HERE eg. MyFile.ashx",{_DateTime:_DateString }).done(function(response){
//Your Response CODE HERE
alert(response);
});
}
}
I'm a little unclear on what you are trying to do.
I think you want something like this:
var timeOut = function() {
****Whatever you want the code to do every 15 minutes****
};
var main = function() {
setInterval(timeOut, 900000);
};
$(document).ready(main);
Note: time is in miliseconds so 1 second = 1000
JSFiddle: http://jsfiddle.net/kitsonbroadhurst/552nu/1/
I have a function to refresh graphs on a page. The idea is that it loops constantly and refreshes a variable called salt. Variables are defined in a separate file and are called path, displayTimeFrom, selectedTimeRangeType and target. Here is the looping code which also responds to changes in the GUI:
$(function () {
refreshGraphs();
});
var refreshGraphs = function () {
d = new Date();
var graphiteUrl = graphs.path + "render/?_salt" + d.getTime()
+ "&from=-" + graphs.displayTimeFrom
+ graphs.selectedTimeRangeType
+ "&minXStep=0"
+ "&until=now&height=800&";
$('#graph-middle').prop("src", graphiteUrl + graphs.target);
setIntervalAndExecute(refreshGraphs, 30000); // refresh every 30000 milliseconds aka every 30 seconds
// Execute immediately and after the interval (setInterval only starts after certain amount of time)
function setIntervalAndExecute(fn, t) {
fn();
return (setInterval(fn, t));
}
// Change graph to chosen value
$('#graph-middle').on('click', '#displayTimeFrom', function () {
graphs.displayTimeFrom = $(this).text();
refreshGraphs();
});
$('#graph-middle').on('click', '#selectedTimeRangeType', function () {
graphs.selectedTimeRangeType = $(this).text();
refreshGraphs();
});
};
When I run it it says "too much recursion". Why is that and how can I solve it?
Your refreshGraphs() function calls itself immediately (via setIntervalAndExecute()) every time it runs.
Two things to note:
1. You're invoking refreshGraphs() recursively.
2. You have placed click handlers in the refreshGraphs() function.
So whenever this refreshGraphs() are invoked it is binding the click events again without unbinding the previous one. You have to either unbind the previous one or you can place them in $(function () {}).
Try any of these.
$(function () {
refreshGraphs();
// Change graph to chosen value
$('#graph-middle').on('click', '#displayTimeFrom', function () {
graphs.displayTimeFrom = $(this).text();
refreshGraphs();
});
$('#graph-middle').on('click', '#selectedTimeRangeType', function () {
graphs.selectedTimeRangeType = $(this).text();
refreshGraphs();
});
});
var refreshGraphs = function () {
d = new Date();
var graphiteUrl = graphs.path + "render/?_salt" + d.getTime()
+ "&from=-" + graphs.displayTimeFrom
+ graphs.selectedTimeRangeType
+ "&minXStep=0"
+ "&until=now&height=800&";
$('#graph-middle').prop("src", graphiteUrl + graphs.target);
setIntervalAndExecute(refreshGraphs, 30000); // refresh every 30000 milliseconds aka every 30 seconds
// Execute immediately and after the interval (setInterval only starts after certain amount of time)
function setIntervalAndExecute(fn, t) {
fn();
return (setInterval(fn, t));
}
};
Or
$(function () {
refreshGraphs();
});
var refreshGraphs = function () {
d = new Date();
var graphiteUrl = graphs.path + "render/?_salt" + d.getTime()
+ "&from=-" + graphs.displayTimeFrom
+ graphs.selectedTimeRangeType
+ "&minXStep=0"
+ "&until=now&height=800&";
$('#graph-middle').prop("src", graphiteUrl + graphs.target);
setIntervalAndExecute(refreshGraphs, 30000); // refresh every 30000 milliseconds aka every 30 seconds
// Execute immediately and after the interval (setInterval only starts after certain amount of time)
function setIntervalAndExecute(fn, t) {
fn();
return (setInterval(fn, t));
}
// Change graph to chosen value
$('#graph-middle').off('click').on('click', '#displayTimeFrom', function () {
graphs.displayTimeFrom = $(this).text();
refreshGraphs();
});
$('#graph-middle').off('click').on('click', '#selectedTimeRangeType', function () {
graphs.selectedTimeRangeType = $(this).text();
refreshGraphs();
});
};
Solution is to call the jQuery in the anonymous function instead of the refreshGraps namespace. Issue solved.