Here I have a simple countdown function that redirects the user after 5 seconds.
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown();
}, 1000);
}
else
{
// Redirect the user
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(target);
</script>
The problem is, when 5 seconds elapse and it's time for the window.location.href to do the redirection, the "target" variable is undefined, I'm not sure why this happens.
I have researched and tried various solutions, even setting the "target" the way "timer" and "counter" are set, but none worked. My goal is to set a different "target" at each function instance.
UPDATE: Setting countdown(); to countdown(target); fixed the "undefined" issue, but the window.location.href object still doesn't redirect to the target variable value, What can be done to fix this?
You need to pass target to countdown in setTimeout
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown(target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
Got it, for some reason, the if (!typeof target === "undefined") still returned true even though target was indeed defined, which caused window.location.href to not fire up and redirect to the target value.
UPDATE: I was doing it the wrong way, it was a grouping issue, but using if (typeof target !== "undefined") makes it work as expected.
I'm sharing the fixed code in case it helps someone else:
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(
function()
{ countdown(target); }, 1000
);
}
else
{
// Redirect the user
if (typeof target !== "undefined")
{
window.location.href = target;
}
}
};
var target = "/MixaPay/";
countdown(target);
</script>
Thanks everyone who have contributed.
Here is your problem, when you call the countdown function again, you should send the "target" object.
setTimeout(function () {
countdown(); // should be: countdown(target);
}, 1000);
try this, its working, you forgot to pass the argument in your function.
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(timer,target){
counter.innerHTML = timer--;
if (timer > 0)
{
setTimeout(function () {
countdown(timer,target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof str === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(timer,target);
try using full url instead of using absolute url to redirect like instead of /account/ use localhost/account/
UPDATE This must work I have tested it
<span id="countdown"></span>
<script>
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown(target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
window.location.href = target;
}
};
var target = "/account/";
countdown(target);
</script>
Related
I'm making a simple program which increases a number incrementally for every 0.5 second. When I click start it works perfectly. But when I click restart, the increments go fine, but they don't increment every 0.5 sec and go pretty fast, and this happens when I am calling the same function? JS fiddle link below.
function runFunc(){
declare a variable interval outside function
var myInterval = null;
check if an interval is already running if yes clear it in order to avoid multiple interval running the same function which makes the interval became looks faster than the first time it's called
if (myInterval != null) {
clearInterval(myInterval);
}
also this is not correct
clearInterval(varName);
the parameter should be an interval which is like this
clearInterval(myInterval);
so your javascript code would be like this
var myInterval = null;
function runFunc(){
$('#counter').val(zero);
var varName = function(){
var number = Number($('#number').val());
var counter = Number($('#counter').val());
if(counter < number) {
counter++;
console.log(counter);
$('#counter').val(counter);
} else {
clearInterval(myInterval);
}
};
//check if an interval is already running if yes clear it
if (myInterval != null) {
clearInterval(myInterval);
}
myInterval = setInterval(varName, 500);
};
show.click(runFunc);
reset.click(function(){
$('#number').val(zero);
$('#counter').val(zero);
});
restart.click(runFunc);
u have to Declare a Variable for setInterval like "setIntervalID"
so stop it clearInterval("setIntervalID");
JSFIDDLE
var initialNumber = 10;
var zero = 0;
$('#number').val(initialNumber);
$('#counter').val(zero);
var show = $('#show');
var reset = $('#reset');
var restart = $('#restart');
var setIntervalID;
// console.log('initial value of number is ' + number);
// console.log(typeof number);
// console.log('initial value of counter is ' + counter);
var varName = function(){
var number = Number($('#number').val());
var counter = Number($('#counter').val());
if(counter < number) {
counter++;
console.log(counter);
$('#counter').val(counter);
}
}
function runFunc(){
$('#counter').val(zero);
setIntervalID = setInterval(varName, 500);
};
function stopFunc(){
clearInterval(setIntervalID);
};
function restartGO(){
stopFunc();
runFunc();
}
show.click(runFunc);
restart.click(restartGO);
reset.click(function(){
$('#number').val(zero);
$('#counter').val(zero);
});
var started = false;
function start() {
var timer;
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
The setInterval works but when I run the function again, it prints in the console that it should be removed. But it doesn't.
timer is declared inside your function, so when you call it again, it's a new instance.
Try declaring it outside the function, like this:
var started = false;
var timer;
function start() {
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
timer gets reinitialized every time you call start so the second time you call it, it's not pointing to a timer id to clear.
use like this
var started = false;
var timer;
function start() {
if(started === false) {
timer = setInterval(decrease, 1000);
started = true;
} else {
clearInterval(timer);
console.log("Should Clear");
}
}
Because timer is in the scope of the function. So when you call it the second time, it is in another scope.
I have some code I am using to countdown from 15 after 15 secs passes it echoes "times over". The problem is if someone clicks twice there will be two counters in the same Div. I need the counter to reset if someone clicks on the button again.
function startCountDown(i, p, f) {
// store parameters
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
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() {
alert("Time Over");
}
HTML:
<div id="TimerTitle">Timer</div>
<span id="countDown"></span>
<button onclick="startCountDown(15, 1000, myFunction);">
Start Time
</button>
Set the timeout as a global variable like so:
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
At the beginning of the function clear the timeout
clearTimeout(timer)
Code:
var timer;
function startCountDown(i, p, f) {
// store parameters
if(timer){clearTimeout(timer)}
var pause = p;
var fn = f;
// make reference to div
var countDownObj = document.getElementById("countDown");
if (countDownObj == null) {
// error
alert("div not found, check your id");
// bail
return;
}
countDownObj.count = function (i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
// stop
return;
}
timer = setTimeout(function(){countDownObj.count(i - 1);},pause);
}
// set it going
countDownObj.count(i);
}
function myFunction() {
alert("Time Over");
}
setTimeout returns an id to the timer that can be used with window.clearTimeout. The simplest solution would be to create a global timerId
var timerId;
...
function startCountDown(i, p, f) {
...
if (timerId) { window.clearTimeout(timerId); }
timerId = window.setTimeout(...);
https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout
I'm trying to create a simple countdown timer. It counts down from the number entered.
However, I'm trying to clear the interval when the counter gets to 0. At the moment it seems to acknowledge the if statement, but not clearInterval().
http://jsfiddle.net/tmyie/cf3Hd/
$('.click').click(function () {
$('input').empty();
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount) + 1;
var timer = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
setInterval(timer, 500);
})
You're not saving the return value of the call to setInterval, which is the value that needs to be passed to clearInterval. Passing the timer handler does no good.
var timer, timerHandler = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
timer = setInterval(timerHandler, 500);
Code looks like that:
function startTimer(counter) {
var interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}
What I want to do is, when I call this function multiple times, every time to reset timer to 30 seconds and kill all past instances. Currently it messes up with past intances when I call multiple times. What am I doing wrong?
You have to define the var interval outside the function:
var interval;
function startTimer(counter) {
interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}