I want to add count down timer to my vue component. I have found a script which is written in normal JavaScript.
this is my JavaScript file.
var upgradeTime = 7200;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
I stored this as a clock.js in my vue js projects src folder.
How do I import this clock.js file to my vue component and get the output.
for this JavaScript code normal way to get output would be something like this
<span id="countdown" class="timer"></span>
But how do I get an output inside a vue component.
I'm junior developer and I haven't clear idea about how to use normal JavaScript inside vue. I hope you understand my question.
Thank you
If you really want a simple and straightforward solution, you can simply put all of that within the mounted callback: that is when the component template has been parsed and the DOM constructed, so #countdown should be accessible by then. Read more about lifecycle hooks in VueJS.
Note: However, if you want to really learn how to use VueJS properly, please continue reading on how to create a custom timer component at the end of this answer :) by stuffing everything into the mounted callback, you are missing out the fun part of authoring your first and rather simple VueJS component.
Before we get started, note that there is a mistake when you invoke timer() in your setInterval callback. It should be:
var countdownTimer = setInterval(timer, 1000);
Here is a proof-of-concept example, where you "turkey stuff" all your timer logic into the mounted() callback:
new Vue({
el: '#app',
template: '#custom-component',
mounted: function() {
var upgradeTime = 7200;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval(timer, 1000);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app"></div>
<script type="text/x-template" id="custom-component">
<div>
<p>I am a custom component.</p>
<p>
My timer:<br />
<span id="countdown" class="timer"></span>
</p>
</div>
</script>
A real ideal solution is to actually create a custom VueJS component for your countdown timer ;) you can do this by simply creating yet another custom component for your timer itself. Some tips and tricks:
Use props so that you can pass in a custom time period
Remember to use data to make a copy of the time period, since you are decrementing the timer, but you cannot mutate props
Use this.$el to refer to your timer component, then you can even make do without the id reference ;)
See proof-of-concept below:
Vue.component('my-timer', {
template: '#my-timer',
props: {
upgradeTime: Number
},
data: function () {
return { seconds: this.upgradeTime }
},
methods: {
timer: function() {
var days = Math.floor(this.seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((this.seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = this.seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
this.$el.innerHTML = hours + ":" + minutes + ":" + remainingSeconds;
if (this.seconds == 0) {
clearInterval(countdownTimer);
this.$el.innerHTML = "Completed";
} else {
this.seconds--;
}
}
},
mounted: function() {
setInterval(this.timer, 1000);
},
});
new Vue({
el: '#app',
template: '#custom-component'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app"></div>
<script type="text/x-template" id="custom-component">
<div>
<p>I am a custom component.</p>
<p>
My timer:<br />
<my-timer upgrade-time="7200"></my-timer>
</p>
</div>
</script>
<script type="text/x-template" id="my-timer">
<span class="timer"></span>
</script>
Better just make a CountdownTimer component out of that code.
Maybe have a look at this post: countdown-timer-using-vuejs
Related
I have a js code and I wanna run it when I click the button.It's seems ok to me but it's run even i don't hit the button.
Probably it has a simple answer but I couldn't handle it.I'm new....
var upgradeTime = 600;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML =
days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Tamamlandı.";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()', 1000);
<span id="countdown" class="timer"></span>
<input id="" type="button" value="clickme" onclick="timer();" />
You need to remove var countdownTimer = setInterval('timer()', 1000);
outside the function:
You can include all your core logic to a new function coreTimer()
Call coreTimer() from timer()
make sure countdownTimer is declared in global scope so that it can be cleared using clearInterval inside coreTimer() function.
var upgradeTime = 10;
var seconds = upgradeTime;
var countdownTimer;
function timer() {
countdownTimer = setInterval('coreTimer()', 1000);
}
function coreTimer() {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = days + ":" + hours + ":" + minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Tamamlandı.";
} else {
seconds--;
}
}
<span id="countdown" class="timer"></span>
<input id="" type="button" value="clickme" onclick="timer();" />
setInterval method calls a function or evaluates an expression at specified intervals. So the statement
var countdownTimer = setInterval('timer()', 1000);
will execute your timer function every 1000 milliseconds. Hence your function is getting called even when you are not clicking the button. You need to modify that statement accordingly or remove it completely.
I want to make a timer that gets its value from an Ajax call. Here is my code:
function timer(seconds) {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds+ "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
console.log(seconds);
}
var countdownTimer = setInterval('timer()', 1000);
}
$.ajax({
type: "GET",
url: "AjaxHandler.php",
dataType: "JSON",
data:{action:"gym"},
success: function(result){
timer(result); // receiving php strtotime(), value something like 150000
},
error:function(){
console.log("Error: Unknown Error")
}
});
Now the problem is that I can't get the value for countdownTimer outside of the scope, so I placed the countdownTimer inside function. But that's not working and I knew that.
Is declaring the seconds value to html object going to work? Like $("#test").val(response)
So my question is: how Can I make this timer work?
Following example demonstrate how you can use a callback function to solve your problem.
function timer(seconds, countdownTimer, callback) {
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds + "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
console.log(seconds);
}
//Pass seconds param back to the caller.
callback(seconds);
}
//Inside the ajax success function you should call following code snippet instead of calling timer(30).
//We pass the countdownTimer param into the timer function as well.
var countdownTimer = null,
seconds = 30;
countdownTimer = setInterval(function() {
timer(seconds, countdownTimer, function(_seconds){
seconds = _seconds;
})
}, 1000);
<div id="countdown"></div>
Well it does not work becuase you call timer() without the seconds in the setTimeout. So you need to pass it.
function timer(seconds)
{
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds+ "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
console.log(seconds);
setTimeout(timer, 1000, seconds);
}
}
timer(30);
<div id="countdown"></div>
But as an FYI, setTimeout is not accurate so the time it ends will be off. So what can you do? Set a date and subtract the current time from it.
function startTimer(seconds) {
var endTime = new Date();
endTime.setSeconds(endTime.getSeconds() + seconds);
timer();
function timer() {
var seconds = Math.ceil((endTime - new Date()) / 1000)
var days = Math.floor(seconds / 24 / 60 / 60);
var hoursLeft = Math.floor((seconds) - (days * 86400));
var hours = Math.floor(hoursLeft / 3600);
var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
var minutes = Math.floor(minutesLeft / 60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = hours + "tundi " + minutes + "minutit " + remainingSeconds + "sekundit";
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
console.log(seconds);
setTimeout(timer, 1000);
}
}
}
startTimer(30);
<div id="countdown"></div>
I am developing a web based system wherein user can give tests submitted by admin, the issue is i want to implement a timer that can initiate at start of the quiz and autosubmit the test as soon as it ends , need help on how do i implement read a lot of aanswers but did not help specific to my project .`
<span id="countdown" class="timer"></span>
<script>
var seconds = 40;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Buzz Buzz";
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
`
counter that i can change time to remain if i want from db
i have a time stamp in table in db that maybe change
now i want for example every 30sec check that and if changed my down-counter changing
my js script is:
<script>
var seconds = 100;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = '0' + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ':' + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = 'Times Up!';
document.getElementById('passage_text').disabled = true;
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
</script>
Try changing this:
var countdownTimer = setInterval('secondPassed()', 1000);
to this:
var countdownTimer = setInterval(secondPassed, 1000);
What isn't working in your case, exactly?
BTW: Try caching reference on frequently used DOM element. See this alternative using much simpler code for formatting your time.
var display = document.getElementById('countdown');
var seconds = 100, timer;
function secondPassed() {
if ( --seconds == 0 ) {
window.clearInterval( timer );
// your code here executing when count down has finished ...
} else {
display.innerHTML = Math.floor( seconds / 60 ) + ':' + String( "0" + ( seconds % 60 ) ).substr( -2 );
}
}
timer = window.setInterval( secondPassed, 1000 );
I have borrowed some JS code to help me create a timer for 65 seconds. My JS knowledge is basic but I managed to modify the script to work the way I want it to. However when I click on the play button the timer speeds up from the second round onwards.
HTML:
<div id="rightCol">
<span id="countdown" class="timer">Timer About to Start! </span>
<div>
<input type="button" value="Play" id="play">
</div>
</div>
JS:
var seconds = 65;
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time's Up!";
document.getElementById("passage_text").disabled = true;
} else {
seconds--;
}
}
var countdownTimer = setInterval('secondPassed()', 1000);
$("#play").click(function(){
seconds = 65;
var countdownTimer = setInterval('secondPassed()', 1000);
$('#passage_text').attr('disabled', false).focus();
$("#passage_text").val('');
});
I read some of the other answers similar to mine Count down timer speeds up but I don't fully understand how the secondPassed() function works to fix it.
You need to clear interval on play functionality too and make countdownTimer global. Also it's better to pass function handler to setInterval instead of string as this will work as eval function and not recommended
var seconds = 65;
var countdownTimer = null; // make it global
function secondPassed() {
var minutes = Math.round((seconds - 30)/60);
var remainingSeconds = seconds % 60;
if (remainingSeconds < 10) {
remainingSeconds = "0" + remainingSeconds;
}
document.getElementById('countdown').innerHTML = minutes + ":" + remainingSeconds;
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Time's Up!";
document.getElementById("passage_text").disabled = true;
} else {
seconds--;
}
}
countdownTimer = setInterval(secondPassed, 1000); // removed var and passing handler instead of string.
$("#play").click(function(){
seconds = 65;
clearInterval(countdownTimer); // clear interval
countdownTimer = setInterval(secondPassed, 1000); // removed var to use global countdownTimer variable
$('#passage_text').attr('disabled', false).focus();
$("#passage_text").val('');
});
See my JS comments above