I'm trying to get my clock to stop at zero and then show results pg. But for now I am unable to get it to stop.
var clock = {
time: 2,
timeleft: 0,
bigben: null,
countDown: function() {
clock.time--;
$("#timer").html(clock.time);
},
start: function() {
bigben = setInterval(clock.countDown, 1000);
},
stop: function() {
// clearInterval(intervalId);
if (time == timeleft) {
window.clearInterval(bigben);
// Display countdown
$('#timer').html(time + "seconds");
time--
}
//end of timer
if (time === timeleft) {
window.clearInterval(bigben);
gameOver();
};
},
You can use setTimeout function. This fonction play his callback when time is at 0.
setTimeout (function () { your code; }, 1000);
1000 is the time in milliseconds
I did not see anywhere you call the stop function.
add clock.stop in your countdown function.
and it seems that in your stop block, the "time", "timeleft" and "bigben" variables are all not reachable....
You need to use clock.time, clock.timeleft, clock.bigben instead.
Try below.
var clock = {
time: 2,
timeleft: 0,
bigben: null,
countDown: function() {
clock.time--;
$("#timer").html(clock.time);
clock.stop();
},
start: function() {
clock.bigben = setInterval(clock.countDown, 1000);
},
stop: function() {
if (clock.time > clock.timeleft) {
$('#timer').html(clock.time + "seconds");
}
if (clock.time === clock.timeleft) {
window.clearInterval(clock.bigben);
//gameOver();
}
}
};
clock.start();
I commented out the gameOver() call, since there is no definition of that function within current code.
Related
I am working on knockout js.
In that i have a recursive function which executes a function every minute. for that am using a timer every 60 sec it will execute also same will be reflecting in the UI also.
In my case, if i try to assign or initialize a timer value(observable) which is inside a loop, it doesn't reflecting instead of reflecting it is added to the pipeline and that much time loop is running simultaneously.
In that case i want to kill the loop and again want to restart every time i am changing the timer value.
timerInSec=60;
var loop = function () {
if (this.timer() < 1) {
myFunction()
this.timer(this.timerInSec - 1);
setTimeout(loop, 1000);
} else {
this.timer(this.timer() - 1);
setTimeout(loop, 1000);
}
};
loop();
Here is my solution. Please check.
timerInSec = 60;
const Loop = (function () {
let timer = 0;
let timerId = -1;
const myFunction = function () {
console.log('finished');
}
const fnLog = function (tm) {
console.log('current time = ', tm);
}
const fnProc = function () {
timerId = setTimeout(myFunction, 1000 * timer);
}
return {
start: function (tm = 60) {
this.stop();
timer = tm;
fnProc();
},
stop: function () {
if (timerId !== -1) {
clearTimeout(timerId);
timerId = -1;
}
}
}
})();
Loop.start(timerInSec);
setTimeout(() => {
Loop.start(timerInSec);
}, 500);
This code should run for 10 seconds before ending, however if you are running the function again before the 10 seconds are finished, it should clear theTimeout and start the 10 seconds over again
function start() {
let counter = 0;
let timeUp = true;
let hello;
setInterval(()=> {
counter++
console.log(counter)
},1000);
if (timeUp == false) {
clearTimeout(hello)
timeUp = true
console.log('should run again with new clock')
start()
} else {
console.log('new clock started')
timeUp = false;
hello = setTimeout(() => {
timeUp = true
console.log('end clock')
}, 10000);
};
};
When you call start() again, this new function has no reference to hello or timeUp
Try it like this:
let hello
let timeUp = true
function start() {
let counter = 0;
//let timeUp = true;
//let hello;
setInterval(()=> {
counter++
console.log(counter)
},1000);
if (timeUp == false) {
clearTimeout(hello)
timeUp = true
console.log('should run again with new clock')
start()
} else {
console.log('new clock started')
timeUp = false;
hello = setTimeout(() => {
timeUp = true
console.log('end clock')
}, 10000);
};
};
window.start = start
Inside your function start, timeUp is always set to true, and thus clearTimeout will never be called. The way you're doing things, you should make timeUp a global variable so the function has "memory" of if the time has been reached or not.
But why do you need to set two intervals? You're already keeping track of the number of seconds that have passed, so we can make use of that interval to determine when 10 seconds have passed. This simplifies things quite a bit, and allows us to get rid of the timeUp variable as well:
let interval;
function start() {
let counter = 0;
clearInterval(interval); // clear the previous interval
interval = setInterval(() => { // set a new interval
counter++;
if (counter == 10) {
console.log('end of clock');
clearInterval(interval);
}
console.log(counter);
}, 1000);
}
This achieves exactly what you want. Whenever start is called, it cancels the previous interval and creates a new one. Once 10 seconds have passed, it clears the interval.
Your approach is kind of misleading. I think a better approach would be to have a Timer Object that you can start:
function Timer() {
var self = {
// Declare a function to start it for a certain duration
start: function(duration){
self.counter = 0;
self.duration = duration;
clearTimeout(self.timeout); // Reset previous timeout if there is one
console.log("New counter starting.");
self.count();
},
// A function to count 1 by 1
count: function(){
console.log(self.counter);
self.counter++;
if(self.counter > self.duration){
console.log('Time is up.');
} else {
self.timeout = setTimeout(self.count, 1000); // not over yet
}
}
// and other functions like stop, pause, etc if needed
};
return self;
}
// Declare your Timer
var myTimer = new Timer();
// Start it on click
document.getElementById('start-btn').addEventListener('click', function(){
myTimer.start(10);
}, true);
<button id="start-btn">Start the timer</button>
Heyho
I have a little issue with my countdown written in Ember. More precisely in stopping my counter when it hits 0.
First of all... I'm using
Ember Version
DEBUG: Ember : 1.12.0
I've created a 'service' Class with some simple methods to handle the countdown process.
interval: function() {
return 10; // Time between polls (in ms)
}.property().readOnly(),
totalTime: function() {
return 5000; // Total Time (in ms)
}.property(),
timeDiff: 0,
timeLeft: function() {
return Math.floor((this.get('totalTime') - this.get('timeDiff')) / 1000);
}.property('timeDiff'),
hasFinished: function() {
return this.get('timeLeft') === 0;
}.property('timeLeft'),
// Schedules the function `f` to be executed every `interval` time.
schedule: function(f) {
return Ember.run.later(this, function() {
f.apply(this);
this.set('timer', this.schedule(f));
}, this.get('interval'));
},
// Starts the countdown, i.e. executes the `onTick` function every interval.
start: function() {
this.set('startedAt', new Date());
this.set('timer', this.schedule(this.get('onTick')));
},
// Stops the countdown
stop: function() {
Ember.run.cancel(this.get('timer'));
},
onTick: function() {
let self = this;
self.set('timeDiff', new Date() - self.get('startedAt'));
if (self.get('hasFinished')) {
// TODO: Broken - This should stop the countdown :/
self.stop();
}
}
CountDown with Ember.run.later()
I'm starting the countdown within my controller (play action).
The countdown counts down as it should but it just doesn't stop :(
The self.stop() call in onTick() just doesn't do anything at all...
I tried to stop the countdown with an other action in my controller and that is working as it should :/
Any ideas how to solve that problem??
Cheers Michael
I've taken the courtesy or writing a Countdown service based on the code you have provided that allows you to start, reset and stop the countdown. My code assumes you are using Ember CLI, but I have included a JSBin that takes older ES5 syntax into account.
app/services/countdown.js
import Ember from 'ember';
const { get, set, computed, run } = Ember;
export default Ember.Service.extend({
init() {
set(this, 'totalTime', 10000);
set(this, 'tickInterval', 100);
set(this, 'timer', null);
this.reset();
},
remainingTime: computed('elapsedTime', function() {
const remainingTime = get(this, 'totalTime') - get(this, 'elapsedTime');
return (remainingTime > 0) ? remainingTime : 0;
}),
hasFinished: computed('remainingTime', function() {
return get(this, 'remainingTime') === 0;
}),
reset() {
set(this, 'elapsedTime', 0);
set(this, 'currentTime', Date.now());
},
start() {
this.stop();
set(this, 'currentTime', Date.now());
this.tick();
},
stop() {
const timer = get(this, 'timer');
if (timer) {
run.cancel(timer);
set(this, 'timer', null);
}
},
tick() {
if (get(this, 'hasFinished')) {
return;
}
const tickInterval = get(this, 'tickInterval');
const currentTime = get(this, 'currentTime');
const elapsedTime = get(this, 'elapsedTime');
const now = Date.now();
set(this, 'elapsedTime', elapsedTime + (now - currentTime));
set(this, 'currentTime', now);
set(this, 'timer', run.later(this, this.tick, tickInterval));
}
});
I've made an example of this implementation available on JSBin for you to toy around with.
I want to change setInterval function time when my code is running.
I try this
<script type="text/javascript">
$(function () {
var timer;
function come() { alert("here"); }
timer = setInterval(come, 0);
clearInterval(timer);
timer = setInterval(come, 10000);
});
</script>
First SetInterval does not work!
You're clearing the interval on the next line, so the first one wont work, as it gets cleared right away :
timer = setInterval(come, 0);
clearInterval(timer);
timer = setInterval(come, 10000);
Also, as gdoron says, setting a interval of nothing isn't really valid, and not a really good idea either, use setTimeout instead, or just run the function outright if no delay is needed.
come();
clearInterval(timer);
timer = setInterval(come, 10000);
You can't. You will need to use setTimeout, and call it repetitively:
var timer; // current timeout id to clear
function come(){ /* do something */};
var time; // dynamic interval
(function repeat() {
come();
timer = setTimeout(repeat, time);
})();
With this you can set a different "interval" to be applied each time the function repeat is executed. Yet, nothing changes if alter time during a timeout, you'd need to stop the timeout for that.
I know this is an old post, but I have implemented a typescript version for changing the interval in run time:
class LoopTimer {
private timer: null | NodeJS.Timer;
private callback: (...args: any[]) => void;
private ms: number;
private started: boolean;
constructor(callback: (...args: any[]) => void, ms: number) {
this.callback = callback;
this.ms = ms;
this.timer = null;
this.started = false;
}
start() {
if (!this.started) {
this.timer = setInterval(this.callback, this.ms);
this.started = true;
}
}
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
this.started = false;
}
}
get getStarted(): boolean {
return this.started;
}
setInterval(ms: number) {
this.ms = ms;
if (this.started) {
this.stop();
this.start();
}
}
}
You can use it like this:
The timer will stop and start again when interval is changed.
const myTimer = new LoopTimer(()=>{
console.log("Hello");
}, 100);
myTimer.setInterval(500);
There is no way to directly change the interval at which a function fires. The best you can do is cancel an interval and set a new one with the same function and updated timer. Here's a possible way of doing it:
timer = {
timers:{},
inc:0,
start:function(cb,gap) {
var key = inc;
inc++;
timer.timers[key] = [setInterval(cb,gap),cb];
return key;
},
stop:function(id) {
if( !timer.timers[id]) return;
clearInterval(timer.timers[id][0]);
delete timer.timers[id];
},
change:function(id,newgap) {
if( !timer.timers[id]) return;
clearInterval(timer.timers[id][0]);
setInterval(timer.timers[id][1],newgap);
}
};
Usage:
var myTimer = timer.start(function() {....},1000);
// calls every second
timer.change(myTimer,5000);
// now calls every five seconds
timer = setInterval(come, 0); // zero isn't a valid interval...
You probably wants:
come();
timer = setInterval(come, 10000);
docs on MDN:
delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.
And:
Historically browsers implement setTimeout() "clamping": successive setTimeout() calls with delay smaller than the "minimum delay" limit are forced to the use at least the minimum delay. The minimum delay, DOM_MIN_TIMEOUT_VALUE, is 4 ms (stored in a preference in Firefox: dom.min_timeout_value), with a DOM_CLAMP_TIMEOUT_NESTING_LEVEL of 5ms.
this is mi example, i think is more simple and easy to understand
const timer = {
time: 5, // 5 time in seconds
_time: null,
_timeout: null,
fun: () => {},
start() {
if (this._timeout == null) {
const self = this;
this.fun();
this._timeout = setTimeout(function repeater() {
self.fun();
self._timeout = setTimeout(repeater, 1000 * self.time);
}, 1000 * this.time);
}
},
stop() {
const timeout = this._timeout;
this._timeout = null;
this.set_time(); // set time to default
clearTimeout(timeout);
},
set_time(time) {
if (this._time == null) this._time = this.time;
if (time) {
this.time = time;
} else {
this.time = this._time;
}
},
};
Explication:
time: is the time of interval between every iteration, cycle or next call
_time: this variable save the default value of time, when use stop(), this variable(_time) restore "time"
start: this function start the iteration, if you call again, it will not duplicate.
stop: this function, stop the timeout and set default time and _timeout
set_time: this function set a new value to time, if you not send a parameter, time restore to default value, declare on running in this example is "5"
example:
const timer = {
time: 5, // 5 time in seconds
_time: null,
_timeout: null,
fun: () => {},
start() {
if (this._timeout == null) {
const self = this;
this.fun();
this._timeout = setTimeout(function repeater() {
self.fun();
self._timeout = setTimeout(repeater, 1000 * self.time);
}, 1000 * this.time);
}
},
stop() {
const timeout = this._timeout;
this._timeout = null;
this.set_time(); // set time to default
clearTimeout(timeout);
},
set_time(time) {
if (this._time == null) this._time = this.time;
if (time) {
this.time = time;
} else {
this.time = this._time;
}
},
};
// print time
timer.fun = () =>{
console.log(new Date())
};
timer.set_time(10)
timer.start()
I know this post is old, but i needed something similar, maybe someone needs it.
This is a version without setInterval, based on the code from the other reaction (Niet the Dark Absol).
function timer()
{
var timer = {
running: false,
iv: 5000,
timeout: false,
cb : function(){},
start : function(cb,iv,sd){
var elm = this;
clearInterval(this.timeout);
this.running = true;
if(cb) this.cb = cb;
if(iv) this.iv = iv;
if(sd) elm.execute(elm);
this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
},
execute : function(e){
if(!e.running) return false;
e.cb();
e.start();
},
stop : function(){
this.running = false;
},
set_interval : function(iv){
clearInterval(this.timeout);
this.start(false, iv);
}
};
return timer;
}
Usage:
var timer_1 = new timer();
timer_1.start(function(){
//magic here
}, 2000, false);
var timer_2 = new timer();
timer_2.start(function(){
//more magic here
}, 3000, true);
//change the interval
timer_2.set_interval(4000);
//stop the timer
timer_1.stop();
The last parameter of the start function is a boolean if the function needs to be run at 0.
You can also find the script here: https://github.com/Atticweb/smart-interval
(function() {
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
var update = document.getElementById("liveUpdate");
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
}, 500);
}
};
count.increment();
})();
It stops but it doesn't go down? What could be the problem?
Your decrement function never updates the output anywhere. The variable is going down but you don't show that on screen.
Try (or check the corresponding JSFiddle):
(function() {
var update = document.getElementById("liveUpdate");
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
update.innerHTML = count.digit;
}, 500);
}
};
count.increment();
})();
setInterval will call the function every 500 seconds. It will not stop until you stop it. You can read more about stopping it at Stop setInterval call in JavaScript
It't not a bug, it's a feature ;-). setInterval() runs the given function in a loop with a given interval (500 ms). See this article for details.