I need to be able to call this function to reset the interval.
I know this has been asked before. But the answer given at
Javascript - Reset setInterval back to 0
is not working for me.
Here is the code that I tried:
function startTimer(){
clearInterval(interval);
var interval = setInterval(function(){
advanceSlide();
}, 5000);
};
I call that at the beginning of my page to start a slideshow that changes every 5 seconds. and I use this code to call it again, witch I expected would reset that 5 seconds.
onclick=startTimer();>
The onclick does one other thing too, but this is what is not working. The other action takes place but the interval does not change, its still going based off the same portion of 5 seconds that was left before I clicked.
You need to declare the variable outside the function...
var interval;
function startTimer() {
clearInterval(interval);
interval = setInterval(advanceSlide, 5000);
}
Otherwise it is lost when the function exits.
Related
I am making a timer in javascript. But there is one thing I am not getting.
Here's the code...
var time = 0;
var timeInterval;
var testTime;
//Main code which increases the value of variable time by 1 every second until interval is stopped
timeInterval = setInterval(function (){
time++;
testTime = time;
}, 1000);
//Code to stop the interval after 10 seconds.
setTimeOut(function() {
clearInterval(timeInterval);
},10000);
//Expected value -> 10
//I get -> 0
console.log(testTime)
If I am running a function which increases the value of time by 1 10times by setInterval() method... Why the value of time is not updating?
When you call setInterval, you are asking code to run after a certain amount of time. The setInterval function is an example of a function that takes a function as a parameter.
This means that you're declaring a function and asking setInterval to call it at a later time all in one go. None of what is inside the function will be called until the interval happens.
Your console.log is not inside either of the functions you gave to setInterval or setTimeout, so it will run straight away.
The order of execution is:
Your variables are declared
Your call to ask setInterval to run your function periodically
Your call to ask setTimeout to run your function after 10 seconds
Your console.log is made
At this point, the execution on your main thread ends
The function you gave to setInterval is called a bunch of times
The function you gave to setTimeout is called once
If you want to fix your code, you can put the console.log in the setTimeout function to ask it to run at the end of the 10 seconds (putting it inside step 7).
var time = 0;
// Main code which increases the value of variable time by 1 every second until interval is stopped
var timeInterval = setInterval(function (){
time++;
console.log("time during interval: ", time);
}, 1000);
// Code to stop the interval after 10 seconds.
setTimeout(function() {
clearInterval(timeInterval);
console.log("time at end: ", time);
}, 10000);
Depending on your objective, you might rather simplify your code by calling clearInterval inside your interval function (if(time > 10) clearInterval(...)) to reduce the likelihood of a bug.
Hello everyone I was wondering how to put a timer into javascript that will count up. I am trying to make a maze game that counts the time that it takes for a user to get to the finish however I can't figure it out. If you have any suggestions let me know, thanks.
You will want to use setInterval and clearInterval when the game is done. You set the setInterval inside of a variable so you can later reference it in clearInterval
// Increase the game timer by 1 second
var gameTimer = window.setInterval(function() {
// Increase your timer here
}, 1000);
// Clears timer
function clearTimer() {
clearInterval(gameTimer)
}
I am currently building a website to host software. What I want is to add to the project pages is a slideshow of screenshots cycling, changing images about every 5 seconds. Is there any way to a script triggered at a time interval using just JavaScript? ..or will I have to resort to alternative methods for achieving my desired functionality.
Thanks in advance for any help!
setInterval:
function doSomething() {
alert('This pops up every 5 seconds and is annoying!');
}
setInterval(doSomething, 5000); // Time in milliseconds
Pass it the function you want called repeatedly every n milliseconds. (setTimeout, by the way, will call a function with a timeout.)
If you ever want to stop the timer, hold onto setInterval’s return value and pass it to clearInterval.
You want the setInterval function.
setInterval(function() {
// This will be executed every 5 seconds
}, 5000); // 5000 milliseconds
Basic reference: http://www.w3schools.com/jsref/met_win_setinterval.asp (please ignore the reference to the "lang" parameter)
More indepth reference: https://developer.mozilla.org/en-US/docs/Web/API/window.setInterval
You can use window.setInterval
Sample usage:
window.setInterval(function () {
console.log("foo");
}, 3000);
It Changes the date time in a div and time changes frequently after 1 sec.
setInterval(function(){
var date=new Date();
$('.class').html(date);
},1000);
I am working on a module in which there is a requirement to show a timer which shows only seconds. The timer must start from 30 and keep on decrementing down to 0; and after that fire some action and again start from 30. How can I achieve this in javascript?
There you go :)
var timer = 30;
function decrementAfter1Second(){
setTimeout(function(){
timer--;
if(timer==0){
doWhateverYouWantAfter30Seconds();
timer = 30;
}
decrementAfter1Second();
}, 1000);
}
decrementAfter1Second();
Now next time you want to do something in javascript don't be a slacker and read something about the language first ;) because right now i'm assuming you either don't know how to program or you don't know how to use google.
You could use setTimeout and clearTimeout. Have the timeout fire every 1 second and then invoke clearTimeout when seconds == 0.
You can find examples of both functions here.
base ={time:0};
var loop = 0;
setInterval(function(){
if(base.time === 9000){
move();
base.time = 0;
}
base.time ++;
},1);
Shouldn't the move(); function occur every 9s? I timed it and its much less, why is that?
setInterval will not run every millisecond. There is a minimum possible interval that is longer than that.
If you want something to run in nine seconds, you should use setTimeout() for 9 seconds. Plus your code doesn't reset base.time back to zero so it would only match 9000 once anyway.
If you want it to run every 9 seconds, then you can use setInterval(handler, 9000) or you can use setTimeout(handler, 9000) and then set the next setTimeout in your handler function.
This will execute move() every nine seconds:
var intervalTimer = setInterval(function(){
move();
}, 9000);
Here's a useful article on the topic: http://www.adequatelygood.com/2010/2/Minimum-Timer-Intervals-in-JavaScript.
To reset the time back to 9 seconds when a button is clicked use this code:
var intervalTimer;
function startTimer() {
intervalTimer = setInterval(function(){
move();
}, 9000);
}
function handleClick() {
clearInterval(intervalTimer); // stop currently running interval
startTimer();
}
startTimer();
See it in action here: http://jsfiddle.net/jfriend00/sF2by/.
Intervals are easy as pie!
var move = function(){
alert("move!");
};
setInterval(move, 9000);
See it work here on jsFiddle
You can't count on setInterval actually running every 1 ms. If the CPU is used for another process, it might not run for 1 second. Instead, use one of the following:
function move() {
// Do stuff.
}
// The obvious solution.
// Certain browsers (Chrome) may put the script in "inactive" mode which will
// pause setInterval code. This means move will be run too few times, if you
// actually depend on it being called X times for Y time.
setInterval(move, 9000);
// The other solution.
// Get the delta between each loop and run the move loop as necessary.
// WARNING: This is not efficient, and you should only use this if you have a
// good reason to do so.
// EXTRA WARNING: This code is actually retarded in its current form. It's just
// here to show you how you'd do it. Since you didn't post your
// original problem, it's hard to know what you're really after.
var time = +new Date, frequency = 9000;
setInterval(function () {
var dt = new Date - time;
// Check if we've waited long enough.
if (dt >= frequency) {
// If the process hangs for 20 seconds, this value would be 2. Usually,
// it will be 1.
// Also, Chrome will pause interval counters, so if a tab is inactive,
// this count could be really high when the tab gets focus again.
var times = Math.floor(dt / frequency);
console.log('Moving', times, 'time(s)!');
for (var i = 0; i < times; i++) {
move();
}
// Start counting time from the last update.
time += times * frequency;
}
}, 1); // 1 could probably be much higher here. Depends on your use case.
You wrote in a comment that there is a button which resets the time, and that's why you don't want to just setTimeout for the full delay. Here's how to handle that:
var running;
function start() {
clearInterval(running);
running = clearInterval(function () {
move();
}, 9000);
}
Every time start() is called, the time will be reset to 9 seconds from now, and if 9 seconds elapse, move() will be called and another 9-second interval will start. If you don't actually want it to happen repeatedly, just use setTimeout instead.
The key is using clearInterval (or clearTimeout) to cancel your previous 9-second-delay and start a new one. It is harmless to call clearInterval with a junk value.