I found this JS-Countdown Script at JSFiddle.
EDIT:
I'm using the code of rafaelcastrocouto now, which is nearly perfect. I wanted a 10-seconds JQuery Countdown-Script with an interval that resets the countdown timer at 5 seconds and starts over again and again, but only for a specific class with a specific id on the whole HTML page. If it drops to 0, the countdown should stop. Also I want to reset specific counters to 10.
It's about a WebSocket that refreshes every second and depending on the data I get for specific counters I want to reset them or they should count down to zero.
New JSFiddle: http://jsfiddle.net/alexiovay/azkdry0w/4/
This is how I solved with jquery and native setInterval...
var setup = function(){
$('.count').each(eachSetup);
};
var eachSetup = function(){
var count = $(this);
var sec = count.data('seconds') ;
count.data('count', sec);
};
var everySecond = function(){
$('.count').each(eachCount);
};
var eachCount = function(){
var count = $(this);
var s = count.data('count');
count.text(s);
s--;
if(s < 0) {
s = count.data('seconds');
}
count.data('count', s);
};
setup();
setInterval(everySecond, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="count" data-seconds="5"></p>
<p class="count" data-seconds="10"></p>
<p class="count" data-seconds="15"></p>
You have sever errors in code, e.g.
setTimeout(cd_go(id), 1000); - should point to function reference not to function execution. setTimeout also returns the timeout id. You must past that id to clearTimeout
clearTimeout(this); it should take id instead of global object (window) or undefined if you are working in strict mode
loop = setInterval(function(id) { … } - id points to undefinded as you are not passing any value for it
Related
i want to take out the result of the count up timer and show it on the page by clicking on button.
Here's my solution for your problem,
I just made a simple counter and then each time I trigger the click event it will show the current timer value
The code:
//initialisation
var counterLabel = document.getElementById("counter");
var valueLabel = document.getElementById("value");
var totalSeconds = 0;
counterLabel.innerHTML = totalSeconds;
//the loop each 1s
setInterval(setTime, 1000);
//the function that will increase the conter value and save it into the cookie
function setTime() {
++totalSeconds;
counterLabel.innerHTML = totalSeconds;
}
//to get the current conter value
function getTime() {
valueLabel.innerHTML = totalSeconds;
}
<label id="counter"></label>
<button onclick="getTime()">save</button>
<label id="value"></label>
Fiddle:
https://jsfiddle.net/871t3w2o/3/
You can also have a look into localstorage and sessionstorage they both work like the cookie but each one has it own advantages and disadvantages and you should choose the one that satisfy your need
I try to disable Apply button when application deadline is over. I used php and I successfully got time on each button. Now different time is print on different button.
<td><input type='submit' value='Apply' id='button' name='button' date-time='$closedate' /></td>
I used jquery/ javascript to disable button after expired time (after deadline of application), it cannot disable and it always enable.
In the code below code I used for disable button but it not works.
<script>
$(document).ready(function() {
var timer = setInterval(function() {
var current = $("#button").data('time');
// get the current value of the time in seconds
var newtime = current - 1;
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
});
</script>
based on what you have put down, it seems there are a few simple errors that need to be looked at
1) looks like a simple typo -- date-time should be data-time
2) you are not actually outputting the value of $closedate try changing it to
without knowing what the value of $closedate is, we won't be able to help further than that
Here is a fiddle that replicates an example...https://jsfiddle.net/o2gxgz9r/6656/
Your main issue is that you are mispelling the data-time attribute in your code as date-time. Your html should be as follows...
<input type='submit' value='Apply' id='button' name='button' data-time='$closedate' />
After fixing that, you should be able to reference the data value. Moreover, you are not updating the data value, so every time setInterval is called, the variable $closedate remains the same, and so the if statement if (newtime <= 0) is never reached...
var timer = setInterval(function() {
// get the current value of the time in seconds
var current = $("#button").data('time');
// decrement the time
var newtime = current - 1;
// update $closedate
$("#button").data('time', newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$("#button").prop('disabled', true);
clearInterval(timer);
} else {
// timer is still above 0 seconds so decrease it
$("#button").data('time', newtime);
}
}, 1000);
I am not sure what the value of $closedate is but I made an assumption in my fiddle.
A few of issues...
First, in your HTML, you have date-time instead of data-time, so when you go to get the attribute later with: $("#button").data('time'), you won't get anything.
Second, you must remember to convert HTML data (which is always a string) to numbers to do math with them.
Third, you need to verify that $closedate is a string that can be converted into a valid number. You indicated in a comment below that $closedate will be something like: 2017-03-17. But that is not a value that you can subtract from.
Lastly, updating the HTML is costly in terms of performance. You are modifying the data-time attribute upon each iteration of your setInterval(), which is roughly every second. This can and should be avoided. It can be done by keeping the time left in a variable instead of writing it back to the document.
Here's a working version:
$(document).ready(function() {
// Always cache references to elements you will use more than once:
var $btn = $("#button");
// When gettting data from HTML, you get strings. You must convert
// them to numbers to do math with them. Also, we are using 5 seconds
// here instead of $closedate for testing purposes.
var current = parseInt($btn.data('time'), 10);
// Initialize the newtime for comparison
var newtime = current;
var timer = setInterval(function() {
newtime--; // Decrease the time left
// Just testing the variables:
console.log(current, newtime);
if (newtime <= 0) {
// time is less than or equal to 0
// so disable the button and stop the interval function
$btn.prop('disabled', true);
clearInterval(timer);
}
current--; // Decrease the counter
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='submit' value='Apply' id='button' name='button' data-time='5'>
I have to show a progressbar/status indicator using pure JavaScript, no jQuery please.
My code is:
<script type="text/javascript">
function processObjects()
{
var selectedRows = {}; // array of selected rows from table
var count = selectedRows.length; // count value exceeds 100
var myDiv = document.getElementById("myDiv");
for(var i=0; i < count; i++)
{
myDiv.innerHTML = (i+1)+"/"+count;
// Process each object from array
// no Ajax call
// takes almost 0.1 sec for each object <- this is not an issue
}
}
</script>
<div id="myDiv"></div>
<input type="button" onclick="processObjects()" value="Process Objects" />
<table>
<!-- Table with lots of rows with checkboxs -->
</table>
Problem:
When I run this script in any Browser, the page becomes unresponsive and does not update the status in using innerHTML as 1/100...2/100...3/100 as so on.
what could be the possible solution to stop browser from becoming unresponsive?
JS is single threaded and it has to take the full attention of the browser while being inside a function.
You need to call long processes through setTimeout() function if you need to give the browser a chance to breath while processing something long.
See how I do this in the following example:
function doProgress(count) {
if (count == 100)
return;
document.getElementById("myDiv").innerHTML = count;
count++;
setTimeout(doProgress, 0, count); //<- calling the same function with new count here. "0" is the milliseconds to call it after. "count" is the argument to pass
}
It only demonstrate this technique and there are lot of best practices to follow once you master it.
Javascript locks the view while code is executing (unless you are using a canvas) so you must end the execution of your code before being able to see results in your DOM.
Even if this article is about angular, the intro explains quite well how javascript works and why it freezes a browser http://jimhoskins.com/2012/12/17/angularjs-and-apply.html
if you want to keep it simple you can do this:
<script type="text/javascript">
var start=0;
var selectedRows = {}; // array of selected rows from table
var count = selectedRows.length; // count value exceeds 100 value
var myDiv = document.getElementById("myDiv");
function processObject(){
myDiv.innerHTML = (++start)+"/"+count;
// Process one object from array using "start" as index
if(start<count){
setTimeout(processObject, 100);
}
}
function processObjects(){
//eventually update values
selectedRows=[] //adds items to array
count = selectedRows.length;
myDiv = document.getElementById("myDiv");
processObject();
}
</script>
<div id="myDiv"></div>
<input type="button" onclick="processObjects()" value="Process Objects" />
<table>
<!-- Table with lots of rows with checkboxs -->
</table>
if you don't want to use global variables you can do this:
function processObject(){
processObject.myDiv.innerHTML = (++processObject.start)+"/"+processObject.count;
// Process one object from array using "start" as index
if(processObject.start<processObject.count){
setTimeout(processObject, 100);
}
}
function processObjects(){
processObject.selectedRows=[]; //array with rows to process
processObject.count=processObject.selectedRows.length
processObject.start=0;
processObject.myDiv=document.getElementById("myDiv");
processObject();
}
Hi i am using Javascript set timeout to run a certain function.
How do i display the last 10 seconds of the timeout when it is nearing the end?
var a = setTimeout('someFunction()', 10000);
Is it able to display something using the value that it store into the variable?
Thanks
I have created a small demo for you,
http://jsfiddle.net/praveen_prasad/DYaan/1/
<div id="target" style="display:none">
target
</div>
var target,
allotedTimeForWork=100 /*you can change this*/
;
var handler = setTimeout(function(){
if(!target)
{
target=document.getElementById('target');
}
target.style.display="block";
startTicker();
}, allotedTimeForWork);
function startTicker()
{
var counter=10;
var tickerHandler= window.setInterval(function(){
if(counter>0)
{
//cache target
target.innerHTML="you have "+counter +" seconds left";
counter--;
}
else
{
target.innerHTML="time over";
clearInterval(tickerHandler);
}
},1000);
}
It is not possible to directly get the remaining time of a Timeout.
You could either try to make multiple Timeouts for every second, or have another variable where you store when the Timeout was started.
I would use two timeouts.
The first with time minus 5 seconds, that calls a function with the second timeout (5 seconds) which would have the timer displayed.
Take a look here: http://jsfiddle.net/VCAnm/
HTML:
<span id="aaa">10</span>
JavaScript:
setInterval(function() {
var elem = document.getElementById('aaa');
elem.innerHTML = elem.innerHTML - 1;
}, 1000);
set 2 timers one for the timeout and another for the warning
var warn_time = 5000;
var function_name = 'someFunction()';
var a = setTimeout('warnFunction(function_name, warn_time)', 10000 - warn_time);
function warnFunction(function_name, time) {
alert('only ' + time + ' seconds left'); //use a div or whatever to display
var b = setTimeout(function_name, time);
}
I'm attempting to run multiple animations (slideshows of sorts) on one page, but the code is only working for one of the (in my case) 3 slideshows that are actually present.
The issue is not with the animation but with the actual initialisation and running of functions (explained better below by looking at the code):
The HTML:
<div class="someclass1" rel="slideshow" type="fade" duration=8500>
<div class="wrapper">...</div>
<div class="wrapper">...</div>
</div>
<div class="someclass2" rel="slideshow" type="slide" duration=4000>
<div class="wrapper">...</div>
<div class="wrapper">...</div>
</div>
<div class="someclass3" rel="slideshow" type="fade" duration=5000>
<div class="wrapper">...</div>
<div class="wrapper">...</div>
</div>
jQuery:
$(function() {
var plays = [];
var duration = 0;
var targets = [];
var t = "";
var $obs = $('div[rel="slideshow"]')
for(var x = 0; x < $obs.length; x++){
$obs.eq(x).children('.wrapper').eq(0).addClass('active');
$obs.eq(x).children('.wrapper').css({opacity: 0.0});
$obs.eq(x).children('.active').css({opacity: 1.0});
$obs.eq(x).children('.navigation a.slide-buttons').eq(0).addClass('current');
// Set duration
duration = $obs.eq(x).attr('duration');
// Set target
targets = $obs.eq(x).attr('class').split(' ');
t = '';
for(var i=0; i<targets.length; i++){
t += '.' + targets[i];
}
if($obs.eq(x).attr('type')==='fade'){
plays[x] = setInterval(function(){fadeSwitch(t);}, duration);
}
else if($obs.eq(x).attr('type')==='slide'){
plays[x] = setInterval(function(){slideSwitch(t);}, duration);
}
}
});
Through testing, I have shown that the loop runs successfully and passes the appropriate target and duration to either fadeSwitch or slideSwitch for all 3 runs of the loop.
fadeSwitch and slideSwitch are identical except for the animation part, for example:
function fadeSwitch(target) {
var $active = $(target+' .active');
if ( $active.length === 0 ){ $active = $(target+' .wrapper:first');}
var $next = $active.next('.wrapper').length ? $active.next('.wrapper')
: $(target+' .wrapper:first');
// FADE ANIMATIONS
$active.animate({opacity : 0.0}, 500, function() {
$active.addClass('last-active');
});
$next.animate({opacity: 1.0}, 500, function() {
$active.removeClass('active last-active');
$next.addClass('active');
});
}
However this function will run only using the last found target (i.e t = '.someClass3'). Even though by placing console.log alerts in the setInterval functions I know that it is applying the correct variables.
e.g.
plays[0] = setInterval(function(){fadeSwitch('.someclass1');}, 8500);
plays[1] = setInterval(function(){fadeSwitch('.someclass2');}, 4000);
plays[2] = setInterval(function(){fadeSwitch('.someclass3');}, 5000);
Yet as I have tried to (badly) explain, if I place a console.log inside of fadeSwitch to test what is being passed as the target when it runs (remember it is set to run after an interval, so by the time the .someClass1 function runs for the first time, the plays[] array is full and finished) the log shows that the target is always .someClass3 and it never succesfully runs for anything else but that last entered target.
Any suggestions or help is greatly appreciated.
Thank you.
The value of t is being "closed over" by your anonymous functions when you call setInterval. For every iteration of your loop you create a new anonymous function, and like you said, at the time t has the right value.
The problem is that by the time each function executes t's value has changed (it will hold the last value of the loops), and all three anonymous functions refer to the same t variable (that is the nature of a closure and the lexical scoping of javascript). The quick fix is to give each anonymous function the right value and not a reference to t:
Change this:
plays[x] = setInterval(function(){fadeSwitch(t);}, duration);
to this:
plays[x] = setInterval((function(t2){ return function(){ fadeSwitch(t2); }; })(t), duration);
And obviously the same for the same line with slideSwitch.
Another thing I felt I should point out: You're using invalid attributes in your html, consider finding an alternative, like hidden embedded markup (e.g. <div class="duration" style="display:none">5000</div>), or class names, or html5 data attributes, instead of <div duration=5000>