JavaScript Countdown Timer Code [JS] - javascript

I'm currently trying to get a countdown timer working but, I don't know JavaScript at all.
<script>
$(document).ready(function (e) {
var $timer = $("#timer");
function update() {
var myTime = $timer.html();
var ss = myTime.split(":");
var dt = new Date();
dt.setHours(0);
dt.setMinutes(ss[0]);
dt.setSeconds(ss[1]);
var dt2 = new Date(dt.valueOf() - 1000);
var temp = dt2.toTimeString().split(" ");
var ts = temp[0].split(":");
$timer.html(ts[1]+":"+ts[2]);
setTimeout(update, 1000);
}
setTimeout(update, 1000);
});
</script>
But I've stumbled upon a problem. So I want it to stop on 00:00, but it continues going.
Also at 2 minutes left and no time remaining I want it to execute some code.
At no time remaining (00:00) I want it to simply redirect to a page and at 2 minutes remaining I want it to run some custom code (Which I have).
But I have no idea on how to make it run at a time and make it stop at a time.
Can anyone help me with this?

Try
$timer.html(ts[1]+":"+ts[2]);
if((ts[1]==="02") &&(ts[2]==="00")){
//custom code at 02:00
}
if((ts[1]==="00") &&(ts[2]==="00")){
//Make the redirect
}
else{
setTimeout(update, 1000);
}
DEMO

The inner function should be a sybling of the anonymous function. Right now update(), can't be called because you are using setTimeout() -> update() should be on the same level as your anonymous function.

Related

How to clear the previous interval and run a new one

I am very new in Node JS, my job is really simple: just clear the exiting interval and run a new on every user button click.
I've tried using global.clearInterval, but it didn't work
function time() {
if (today.getTime() === subuh.getTime()){
admin.messaging().sendToDevice(token, notifikasi)
}
console.log(today.toTimeString)
}
clearInterval(clock);
var clock = setInterval(time, 1000);
What I expect is var clock is cleared before setInterval
Please help me, help me solve this and make me sleep
I think you need two functions here: one will be called when the user clicks the button (I called it restart()) - it will clear the previous timer and start a new one. And the second function is what you actually want to be repeated every second and what you pass to the setInterval (I just log the current timer id).
Check out this example:
var timer;
function time() {
console.log('Timer ID:', timer);
}
function restart() {
clearInterval(timer);
timer = setInterval(time, 1000);
}
<button onclick="restart()">(Re)start</button>
Before your call to clearInterval(clock); the variable clock does not exist as such you should get a reference error of clock not being defined. You can however be able to clear value of clock after the call to set interval. this is because the variable clock only start existing after the call to set var clock = setInterval(time, 1000); Alternatively, you could define clock before you call clearInterval.
function time() {
if (today.getTime() === subuh.getTime()){
admin.messaging().sendToDevice(token, notifikasi)
}
console.log(today.toTimeString)
}
var clock;
clearInterval(clock);
clock = setInterval(time, 1000);
Either way, it is the same as doing this
var clock = setInterval(time, 1000); and clearing the interval at some point when some certain event occur.

I want to repeat a function using for loop but the for loop does nothing

I'm coding a game using HTML,CSS and JavaScript. And I've create a function that countdown a p-tag in the HTML code but it subtract just one number every time the function executed, so i need to execute this function a lot of time and when the countdown rich zero the game finish.
I've tried to put a for loop in but the for loop does nothing.
My JavaScript function :
function time() {
for (i=0;i<30;i++) {
var enem = document.getElementById("enem");
var timer = document.getElementById("timer1").innerHTML;
var timer = parseInt(timer);
var actime = timer - 1;
sleep(1000).then(() => {
timer = document.getElementById("timer1").innerHTML = actime;
if (timer===0) {
enem.parentNode.removeChild(enem);
window.location.href = ('success.html');
}
})
}
}
I except the result of time() function will change the p-tag every 1 second 30 time, but it change just one time.
You should use Javascript's setInterval function for it.
(function(){
var n = 30;
var tm = setInterval(countDown,1000);
var enem = document.getElementById("enem");
var timer = document.getElementById("timer1");
function countDown(){
n--;
if(n == 0){
clearInterval(tm);
enem.parentNode.removeChild(enem);
window.location.href = ('success.html');
}
timer.innerHTML = n;
}})();
<p id="enem"></p>
<p id="timer1"></p>
You’re looking for setInterval(), which is the way Javascript perform a certain action every specific period of time.
The code you posted won’t work because of the non-blocking nature of Javascript, it will schedule the sleep function call, and move along with the next loop.

Countdown end case resulting in Javascript error

I have a simple countdown plugin which counts down second by second to a time, and upon reaching that time it runs a callback function of my choosing.
What I have discovered today is that if I have two countdowns on the same page, and one countdown finishes, a javascript error occurs because a variable becomes undefined, which also breaks the second countdown.
Here's the code:
(function($) {
$.fn.countdown = function(options, callback) {
var $self = $(this);
var settings = {
'date' : null,
}
if(options) {
$.extend(settings, options);
}
function countdownProcessor() {
var eventDate = Date.parse(settings.date) / 1000;
var currentDate = Math.floor($.now() / 1000);
if (eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
var secondsBetween = eventDate - currentDate;
// processing logic here.
}
countdownProcessor();
interval = setInterval(countdownProcessor, 1000);
}
})(jQuery);
The issue is with the if statement which checks to make sure the date has not already occurred:
if (eventDate <= currentDate) {
callback.call(this);
clearInterval(interval);
}
When this condition becomes true, the callback completes successfully, but clearInterval does not because the variable interval is not defined - this is because the countdown function is run before interval is declared.
I've tried fixing it by switching the interval variable declaration and countdownProcessor(); around, but this doesn't help because it simply causes the first, ended countdown to count into the negatives.
I've a few other methods like changing the scope and order of declaration of some of the code, but it invariably leads to the countdown either A) counting into the negatives, or B) still erroring out.
How can I fix this?
Add var:
var interval = setInterval(countdownProcessor,1000);
This makes the interval local to each countdown that is being run, rather than global to the entire page.

Javascript timer algorithm help, do something once, then clearInterval

On mousemove or scroll I want to reset a timer if it's not running and inside the timer function run a function once. So far I have this...
var timerId,
lastActive = new Date().getTime(),
token;
var timerFunc = function () {
var currentTime = new Date().getTime();
var timeDiff = currentTime - lastActive;
if (timeDiff > 10000) {
//clearInterval(timerId);
}
//I want to do some logic here
// but only on the first iteration of the timer
//how can I do that?
};
$(window).on('mousemove scroll', function (e) {
lastActive = new Date().getTime();
//only restart the timer if its not currently running. How can I do that??
if(resetTimer)
timerId = setInterval(timerFunc , 10000);
});
timerId = setInterval(timerFunc , 10000);
Can any javascript gurus help me fill in the pieces? I apologize if I'm too brief. I will follow up any questions in the comments. Thank you all for any tips, links, tricks, etc.. Cheers. =)
I'd make use of a boolean variable for first interval(that's easy, just add it after the timer. You've got the right idea in the if(resetTimer) too, to check if it's running just have the timer function set a global variable when it's running and when it stops.

Putting a setInterval when a function called

var now = new Date();
var millisTill10 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 1, 20, 00, 0) - now;
function openAPage() {
var startTime = new Date().getTime();
var myWin = window.open("http://google.com","_blank")
var endTime = new Date().getTime();
var timeTaken = endTime-startTime;
document.write("<br>button pressed#</br>")
document.write(startTime);
document.write("<br>page loaded#</br>")
document.write(endTime);
document.write("<br>time taken</br>")
document.write(timeTaken);
myWin.close()
}
function beginSequence() {
openAPage();
setInterval(openAPage, 5000);
}
setTimeout(beginSequence, millisTill10);
This is my JS code. I am opening a web page with setTimeout as you see. But after then I want to put an internal for example I will call openAPage function every 1 minute after setTimeout statement. How will I do it? Can anyone fix my code?
setTimeout(startOpeningPages, millisTill10);
function startOpeningPages() {
openAPage();
setInterval(openAPage, 60 * 1000);
}
I realize there are a lot of correct answers already. I'll post this anyway for kicks :)
function() {
var win = window.open("about:blank")
var doc = win.document
doc.write("Hello")
setTimeout(arguments.callee, 60*1000)
}()
These are 2 of the my favorite things you can do in Javascript: Self-invoke a function (the ending () after the function declaration, and being able to access the anonymous function from within the function through arguments.callee.
This is better than setInterval in that the first process has to be completed and then 60s later, the second process starts. With setInterval, the process just keeps starting every 60s. 60s is a large interval where this wouldn't matter as much, but this usually matters a lot more with smaller times (in the ms ranges). Because it might end up buffering the second function to execute before the first one is complete.

Categories