I created ajax to get start time and end time from another page and setInterval for this function every second like this.
setInterval(function () {
CheckTime()
}, 1000);
function CheckTime() {
$.ajax({
url: "Get_TIme.php",
success: function (result) {
var time = result.split('|');
var start_time = time[0];
var end_time = time[1];
var getTime = new Date();
var currentHours = getTime.getHours();
var currentMinutes = getTime.getMinutes();
var currentTime = currentHours + ":" + currentMinutes;
if ((currentTime == start_time) || (currentTime == end_time)) {
$('#first').load('demo.php #first'); //reload div
}
}
});
At first time when current time = start time, <div> can refresh itself. But when current time = end time, <div> doesn't reload itself. I don't what happen on this code. But I replace alert before if((currentTime==start_time)||(currentTime==end_time)) like this:
alert("something");
if((currentTime==start_time)||(currentTime==end_time))
{
$('#first').load('demo.php #first'); //reload div
}
<div> can reload itself when current time = end time. Anyone can suggest me what happen on my code.
I think load must be use like that :
$('#first').load('demo.php');
this is what I saw in the documentation here
Try this:
if((currentTime==start_time)||(currentTime==end_time))
{
$('#first').load('demo.php'); //reload div
}
if you want show #first use following;
$(document).ready(function(){
$("#first").css("class","active");
}
Related
hello i am trying to make a countdown which refreshes the page when the countdown finished
however the timer is not refreshing page when countdown ends it start more counting in clock wise
for example the timer has to reload the page after 3 , 2 ,1 , but it goes like 3, 2, 1 , 1, 2 ,3 and so on below is my code
<?php if (isset($alert)) { ?>
<script type='text/javascript'>$('#alert').modal('show');</script>
<?php } ?>
<script type="text/javascript" src="template/js/site.js"></script>
<script type="text/javascript">
$("#DateCountdown").TimeCircles();
$("#CountDownTimer").TimeCircles({ time: { Days: { show: false }, Hours: { show: false } }});
$("#PageOpenTimer").TimeCircles();
var updateTime = function(){
var date = $("#date").val();
var time = $("#time").val();
var datetime = date + ' ' + time + ':00';
$("#DateCountdown").data('date', datetime).TimeCircles().start();
}
$("#date").change(updateTime).keyup(updateTime);
$("#time").change(updateTime).keyup(updateTime);
$(".startTimer").click(function() {
$("#CountDownTimer").TimeCircles().start();
});
$(".stopTimer").click(function() {
$("#CountDownTimer").TimeCircles().stop();
});
$(".fadeIn").click(function() {
$("#PageOpenTimer").fadeIn();
});
$(".fadeOut").click(function() {
$("#PageOpenTimer").fadeOut();
});
</script>
setTimeout(function() {
window.location.reload();
}, 1500)
Swap out the 1500 for the time in ms that you want to pass before reloading the page.
Can't see timeout/interval routines in your code, so I'll show my example to do what you want:
// your timeout in seconds
var timeSec = 10;
// fix countdown start time in seconds
var timeStart = parseInt((new Date()).getTime() / 1000);
// function to check if time is up
function TimeCheck() {
// get time left in seconds
var timeLeft = timeSec - (parseInt((new Date()).getTime() / 1000) - timeStart);
// checking if time is up
if(timeLeft > 0) {
// if time is not up yet
// ... do whatever you want to display / refresh time left to reload page ...
// set "check timeout" for next check
setTimeout(TimeCheck, 1000);
}
else {
// reload page and don't set "check timeout" again
window.location.reload();
}
}
// initial timeout start
cTimeout = setTimeout(TimeCheck, 1000);
Using setTimeout() instead of setInterval() prevents multiple instances of callback functions to stuff in execution queue.
Maybe you mean this code to solve the problem?
$("#CountDownTimer")
.TimeCircles({count_past_zero: false}) // prevent countdown below zero
.addListener(countdownComplete); // add "countdown complete listener"
function countdownComplete(unit, value, total){
if(total <= 0){
// ... make your page refresh ...
}
}
I have basic understanding of javascript and jquery, but so far all i have done is client side validation and occasional ajax call to servlet. I need to display multiple countup timers(dynamically generated).
My page will have many timers(each with their own start/pause/resume/stop buttons). I am able to start the timers individually, but unable to pause them individually.
Referred this link from stackoverflow.(http://jsfiddle.net/6nv3qy88/)
I created another setting "pause:null" in the above plugin.
(function($) {
$.fn.upCount = function(options, callback) {
var settings = $.extend({
startTime: null,
resume: null,
pause: false
}, options);
var container = this;
globalContainer = container.parent().html();
var currentDate = function() {
// get client's current date
var date = new Date();
return date;
};
if(settings.startTime){
resumeTimer(new Date(settings.startTime));
}
var original_date = currentDate();
var paus = settings.pause;
if(paus){
alert("In settings.pause" + paus);
var target_date = new Date('12/31/2014 12:00:00');
paus = true;
}else{
var target_date = new Date('12/08/2015 14:55:00'); // Count up to this date
}
// Given a start time, lets set the timer
function resumeTimer(startTime){
alert('Resume Timer Needs to Start From StartTime ' +startTime)
}
// Start the counter
function countUp() {
// Set our current date
var current_date = currentDate();
//alert("In countUp paus--" + paus);
// difference of dates
var difference = current_date - new Date(settings.startTime);
if (current_date >= target_date) {
// stop timer
alert("In stop timer --" + target_date);
clearInterval(interval);
interval = 0;
if (callback && typeof callback === 'function') callback();
return;
}
//Code for Counting timer
};
interval = setInterval(countUp, 1000);
};
})(jQuery);
I am able to start the timers individually independent of each other based on rowIndex and start button id.
My code for starting timer:
function startTimer(id, rowIndex){
var startTimeId = 'id="list:'+rowIndex+':projectStartTime"';
var y = $('['+startTimeId+']').text();
//alert("value of y##" + y);
if(y.length > 0){
//$('#'+id).upCount({startTime: '12/04/2015 07:00:00', resume: true});
$('#'+id).upCount({startTime: $('['+startTimeId+']').text()});
}
}
Above code helps me start multiple timers independently. But I am unable to pause the timers individually. If I click on any pause all timers stop. I use clearInterval(interval)
for pausing the timers.
pause function:
function pause(id, rowIndex){
alert("In Function" + id);
var timer = $('#'+id+' span').text();
$('#'+id).upCount({startTime: '12/04/2015 07:00:00',pause: true});
}
Help needed for:
I would like to know how to clear interval only for the row from which the button is clicked i.e. the timer should pause once pause button is clicked.
JSF commandButton code:
<p:commandButton id="startBtn" action="#{timeBB.addTask}" value="Start" style="align:center;" styleClass="button" onstart="startTimer(#{impl.timerId},#{rowIndex});">
<f:param name="currentRow" value="#{impl.timerId}"/>
</p:commandButton>
<p:commandButton id="pauseBtn" value="Pause" action="#{timeBB.pause}" style="align:center;" styleClass="buttonStyle" onstart="pause(#{impl.timerId},#{rowIndex});">
<f:param name="currentProjectRowIndex" value="#{impl.timerId}" />
</p:commandButton>
Can anyone point out what I am doing wrong here?
just need a little help here. My problem is, how can I count the seconds when i hover a specific element. Like for example when I hover a button, how can i count the seconds did i stayed in that button after I mouseout?
An alternate solution using setInterval. DEMO HERE
var counter = 0;
var myInterval =null;
$(document).ready(function(){
$("div").hover(function(e){
counter = 0;
myInterval = setInterval(function () {
++counter;
}, 1000);
},function(e){
clearInterval(myInterval);
alert(counter);
});
});
A simple example
var timer;
// Bind the mouseover and mouseleave events
$('button').on({
mouseover: function() {
// set the variable to the current time
timer = Date.now();
},
mouseleave: function() {
// get the difference
timer = Date.now() - timer;
console.log( parseFloat(timer/1000) + " seconds");
timer = null;
}
});
Check Fiddle
How about this quick plugin I just knocked out, which will work on multiple elements, and without using any global variables:
(function($) {
$.fn.hoverTimer = function() {
return this.on({
'mouseenter.timer': function(ev) {
$(this).data('enter', ev.timeStamp);
},
'mouseleave.timer': function(ev) {
var enter = $(this).data('enter');
if (enter) {
console.log(this, ev.timeStamp - enter);
}
}
});
};
})(jQuery);
Actually disabling the functionality is left as an exercise for the reader ;-)
Demo at http://jsfiddle.net/alnitak/r9XkX/
IMHO, anything using a timer for this is a poor implementation. It's perfectly trivial to record the time without needing to use an (inaccurate) timer event to "count" seconds. Heck, the event object even has the current time in it, as used above.
This is exam:
var begin = 0;
var end = 0;
$('#btn').hover(function () {
begin = new Date().getTime();
});
$('#btn').leave(function () {
end = new Date().getTime();
sec = (end - begin) / 1000;
alert(sec);
});
One way to go about it would be the event.timeStamp method :
var initial_hover, exit_hover;
$('#ele').hover(
function(event){
initial_hover = event.timeStamp
console.log(initial_hover);
},
function(event){
exit_hover = event.timeStamp
$(this).html(exit_hover - initial_hover);
console.log(exit_hover);
}
);
jsfiddle
You've tagged the question with JQuery, so here's a jQuery solution.
$(element).on('mouseover', function(e){
$(e.target).data('hover-start', new Date().getTime());
});
$(element).on('mouseout', function(e){
// count the difference
var difference = new Date().getTime() - $(e.target).data('hover-start');
// clean up the data
$(e.target).data('hover-start', undefined);
console.log('Mouse was over for', difference/1000, 'seconds');
});
use setInterval and store value in variable. call the function on mouserover.
function mouseover(){
var start = 0;
setInterval(function(){
start++;
var count = start;
}, 1000);
}
This may not be the place for this question, but here goes anyways.
I am trying to learn more about the JS timers and am using the JS Fiddle for this purpose. In my script, I am using a script that binds functionality to a few elements, but I need the JS Fiddle to not execute it until the page loads completely due to it needing all elements to be initialized and available (see my fiddle at: http://jsfiddle.net/radi8/W2b2M/4/). This fiddle is a VERY rough skeleton.
The format of the script is as follows:
How can I make the JS Fiddle only load this after all other elements are finished?
$(document).ready(function() {
var tmr = {
init: function(){
},
somefunct1: function(){
},
somefunction2: function(){
}
};tmr.init();
});
Any help is appreciated.
document.ready() is the way to good. However, there are other issues with your code. This function is not defined correctly:
function stopTimer {
clearInterval(timer);
}
Should be:
function stopTimer() {
clearInterval(timer);
}
Also, startstop.value is not defined. What is startstop suppose to be?
Update
Your use of .val() is incorrect, and many other issues (fixed):
http://jsfiddle.net/W2b2M/17/
Check this Fiddle:
A simple Javascript Function to Set timer.
$(document).ready(function () {
var input = 120;
function calculateTime(timer) {
var timer = timer;
var mins = Math.floor(timer / 60);
var secs = timer % 60;
var time = (mins < 10 ? "0" : "") + mins + ":" + (secs < 10 ? "0" : "") + secs;
return time;
};
setInterval(function () {
data = calculateTime(input)
if (input > 0)
{
$("#timer").text(data);
input--;
}
else
{
$("#timer").text("Time Out, Njoy Coding in JavaScript")
}
}, 1000);
});
http://jsfiddle.net/MUMU1987/sUkjj/
hey, how can I have my download link hidden, and make a count down type thing. Maybe have it count down from 10 and once it's done that have the download link appear, it would be best to do it in js right?
does anyone know how to do this? :D
Thanks
Complete example:
<span id="countdown"></span>
<a id="download_link" href="download.zip" style="display:none;">Download</a>
<noscript>JavaScript needs to be enabled in order to be able to download.</noscript>
<script type="application/javascript">
(function(){
var message = "%d seconds before download link appears";
// seconds before download link becomes visible
var count = 10;
var countdown_element = document.getElementById("countdown");
var download_link = document.getElementById("download_link");
var timer = setInterval(function(){
// if countdown equals 0, the next condition will evaluate to false and the else-construct will be executed
if (count) {
// display text
countdown_element.innerHTML = "You have to wait %d seconds.".replace("%d", count);
// decrease counter
count--;
} else {
// stop timer
clearInterval(timer);
// hide countdown
countdown_element.style.display = "none";
// show download link
download_link.style.display = "";
}
}, 1000);
})();
</script>
You can use setInterval for this. setInterval behaves like a timer, where you can run a certain function periodically. Something like this should do the work(untested):
$(".link").hide();
var iteration = 0;
var timer = setInterval(function() {
if(iteration++ >= 10) {
clearTimeout(timer);
$(".link").show();
$(".counter").hide();
}
$(".counter").text(10 - iteration);
}, 1000);
This will initially hide the download link and run a function every second which counts down from 10. When we reaced ten, we hide the counter and show the link. ClearTimeout is used so that we don't count after we reached ten. Easy as dell.
Edit: As mentioned in the comments, this function is using jQuery to find the elements.
Take a look at the setTimeout function. You can do something like:
function displayLink() {
document.getElementById('link_id').style.display = 'block';
}
setTimeout(displayLink, 10000);
var WAIT_FOR_SECONDS = 10;
var DOWNLOAD_BUTTON_ID = "btnDownload";
if (document.body.addEventListener) {
document.body.addEventListener("load", displayDownloadButton, false);
} else {
document.body.onload = displayDownloadButton;
}
function displayDownloadButton(event) {
setTimeout(function() {
_e(DOWNLOAD_BUTTON_ID).style.display = "";
}, WAIT_FOR_SECONDS*1000);
}
function _e(id) {
return document.getElementById(id);
}