im trying to create a counter, the problem is that im trying to make the counter run only if the user is in the window, if the user goes out of the window or to another separator the counter should stop untill he comes back.
Here is my code:
$(window).blur(function(){
console.log("Counter Should Stop");
});
$(window).focus(function(){
window.onload = function(){
(function(){
var counter = 10;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
// Display 'counter' wherever you want to display it.
if (counter === 0) {
alert('this is where it happens');
clearInterval(counter);
}
}, 1000);
})();
}
});
You've got some scoping issues, as well as nested function issues. For readability, as well as helping you debug, I'd recommend refactoring it into separate function names for each event. This also helps promote reusability.
This should do what you're looking for:
(function(){
// your global variables
var span = document.getElementById("count");
var counter = 10;
var timer;
// your helpers
var startTimer = function() {
// do nothing if timer is already running
if (timer) return;
timer = setInterval(function() {
counter--;
if (counter >= 0) {
span.innerHTML = counter;
}
// Display 'counter' wherever you want to display it.
if (counter === 0) {
alert('this is where it happens');
stopTimer();
}
}, 1000);
};
var stopTimer = function() {
clearInterval(timer);
timer = null;
};
// your handlers
var onBlur = function() {
stopTimer();
};
var onFocus = function() {
startTimer();
};
var onLoad = function() {
startTimer();
};
// assign your handlers
$(window).load(onLoad);
$(window).blur(onBlur);
$(window).focus(onFocus);
})();
Related
Below in the code is an array of pages which is shuffled and then each of them is displayed in an iframe for a certain amount of time. I want to be able to start/stop the pageChange function using a button or a mouse click. Can anyone help me with this? Below is the working code, or check this fiddle: http://jsfiddle.net/xaa1qccm/ (Thanks to Nobe4)
var pages=[];
pages[0]="http://example.com/";
pages[1]="http://www.iana.org/domains/reserved";
pages[2]="http://en.wikipedia.org/wiki/Main_Page";
pages[3]="http://en.wikipedia.org/wiki/Randomness";
var shuffle = function(array){
var shuffledPages = [];
while(array.length){
shuffledPages.push(array.splice(Math.floor(array.length*Math.random()),1));
}
return shuffledPages;
}
var time = 3300;
var currentIndex = 0;
function pageChange() {
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
setTimeout(function() { pageChange(); }, time);
};
pageChange();
A variable which can be set to determine if the rotator is running, and setting that to true or false:
var isRunning = true;
....
<button onclick="isRunning = false">stop</button>
<button onclick="isRunning = true">start</button>
And check that inside your method:
function pageChange() {
if(isRunning){
...
}
setTimeout(function() { pageChange(); }, time);
};
Live example: http://jsfiddle.net/xaa1qccm/1/
You may add a start/stop variable so as to check the status :
[...]
var time = 3300;
var currentIndex = 0;
var stop = 0;
function pageChange() {
if(currentIndex == 0){
pages = shuffle(pages);
console.log(pages);
currentIndex = pages.length;
}
if (stop == 0)
{
currentIndex--;
document.getElementById("frame").src=pages[currentIndex];
console.log(currentIndex);
setTimeout(function() { pageChange(); }, time);
}
};
function startStop()
{
if (stop == 0){
stop = 1;
}
else{
stop = 0;
pageChange();
}
}
[...]
And then you call startStop() on the click event of the button you want
Edit : Here is a jsfiddle
i need a JavaScript, that relaods a page every 30 seconds, and will show how much time there is until next reload at the ID time-to-update, Example:
<p>Refreshing in <span id="time-to-update" class="light-blue"></span> seconds.</p>
i also need it to repeat itself infinitely.
thank you for reading, i hope it helps not me but everyone else, and a real big thank you if you could make this script.
(function() {
var el = document.getElementById('time-to-update');
var count = 30;
setInterval(function() {
count -= 1;
el.innerHTML = count;
if (count == 0) {
location.reload();
}
}, 1000);
})();
A variation that uses setTimeout rather than setInterval, and uses the more cross-browser secure document.location.reload(true);.
var timer = 30;
var el = document.getElementById('time-to-update');
(function loop(el) {
if (timer > 0) {
el.innerHTML = timer;
timer -= 1;
setTimeout(function () { loop(el); }, 1000);
} else {
document.location.reload(true);
}
}(el));
http://jsfiddle.net/zGGEH/1/
var timer = {
interval: null,
seconds: 30,
start: function () {
var self = this,
el = document.getElementById('time-to-update');
el.innerText = this.seconds; // Output initial value
this.interval = setInterval(function () {
self.seconds--;
if (self.seconds == 0)
window.location.reload();
el.innerText = self.seconds;
}, 1000);
},
stop: function () {
window.clearInterval(this.interval)
}
}
timer.start();
I'm officially stuck. I can't seem to get the stopTimer() function to work properly. Any help would be greatly appreciated. Thanks!
http://jsfiddle.net/4Efbd/1/
var counter;
function stopTimer() {
window.clearInterval(counter);
$('#queryTimer').html('');
}
function startTimer() {
var count = 60;
var counter = setInterval(function () {
count = count - 1;
if (count <= 0) {
window.clearInterval(counter);
return;
}
$('#queryTimer').html('Requery in:' + count + ' Seconds.');
}, 1000);
}
$('#start').click(function () {
startTimer();
});
$('#stop').click(function () {
stopTimer();
});
var counter = setInterval(function () {
That says "create a new variable counter". This means that the existing variable never gets changed, so clearInterval doesn't have the right identifier to clear it. You want to use the existing variable:
counter = setInterval(function () {
I want my countdown to stop on the click of a submit button, i searched in some pages,
but I didn't found anything.
Here is the code i want to stop on click
function countDown (count) {
if (count > 0) {
var d = document.getElementById("countDiv");
d.innerHTML = count;
setTimeout (function() { countDown(count-1); }, 1000);
document.getElementById('tiempo').value = count;
}
else
document.location = "timeover.php";
}
document.getElementById("palabra").focus();
countDown(5);
</script>
You have to save reference to timeout (actually return value of timeout will be number) and use it to cancel timeout.
var timeout = window.setTimeout(function () {
// do something
}, 1000);
// clear timeout
window.clearTimeout(timeout);
You probably got the idea. By the way, you should probably look at setInterval method since it would be better in this situation. Interval will "tick" as long until you cancel it.
Try something like this:
var stopped = false;
function countDown (count) {
if (count > 0) {
var d = document.getElementById("countDiv");
d.innerHTML = count;
document.getElementById('tiempo').value = count;
if (!stopped) {
setTimeout (function() { countDown(count-1); }, 1000);
}
}
else
document.location = "timeover.php";
}
document.getElementById("palabra").focus();
document.getElementById("mySubmitId").onclick = function () {
stopped = true;
};
countDown(5);
I am trying to figure out a way to make my countdown timer restart at 25 all over again when it reaches 0. I dont know what I am getting wrong but it wont work.
Javascript
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
//write out count
countDownObj.innerHTML = i;
if (i == 0) {
//execute function
fn();
//stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
//set it going
countDownObj.count(i);
}
function myFunction(){};
</script>
HTML
<div id="countDown"></div>
try this, timer restarts after 0
http://jsfiddle.net/GdkAH/1/
Full code:
window.onload = function() {
startCountDown(25, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(25, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};
​
I don't see you resetting the counter. When your counter goes down to 0, it executes the function and return. Instead, you want to execute the function -> reset the counter -> return
You can do this by simply adding i = 25 under fn() :
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
i = 25;
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
},
pause
);
}
// set it going
in #Muthu Kumaran code is not showing zero after countdown 1 . you can update to this:
if (i < 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
The main reason for using setInterval for a timer that runs continuously is to adjust the interval so that it updates as closely as possible to increments of the system clock, usually 1 second but maybe longer. In this case, that doesn't seem to be necessary, so just use setInterval.
Below is a function that doesn't add non–standard properties to the element, it could be called using a function expression from window.onload, so avoid global variables altogether (not that there is much point in that, but some like to minimise them).
var runTimer = (function() {
var element, count = 0;
return function(i, p, f) {
element = document.getElementById('countDown');
setInterval(function() {
element.innerHTML = i - (count % i);
if (count && !(count % i)) {
f();
}
count++;
}, p);
}
}());
function foo() {
console.log('foo');
}
window.onload = function() {
runTimer(25, 1000, foo);
}