I am trying to create a countdown using javascript. I got some code from here and modified it slighly.
<script type="text/javascript">
var c=10, t;
function timedCount() {
document.getElementById('txt').value=c;
c=c-1;
t=setInterval("timedCount()",1000);
}
function stopCount() {
clearInterval(t);
}
</script>
I need to call a countdown repeatedly until the user clicks on a link. It should countdown from 10 by 1 every second (10,9,8,7,6...0) until the link is clicked but it doesn't. Can anybody help me?
EDIT:
Does anyone know how to make the countdown restart once it hits 0?
Thank you in advance.
<script type="text/javascript">
var c=10;
var t;
function timedCount()
{
document.getElementById('txt').value=c;
c=c-1;
}
function startCount()
{
if (!t) t=setInterval("timedCount()",1000);
}
function stopCount()
{
clearInterval(t);
t=null;
}
</script>
Call startCount() in onload (or whatever) when you want the counter started. Note my startCount and stopCount don't create multiple interval timers.
Also, the element with id=txt needs to be an <input> or <textarea> box for your code to work. If it's a span, you should use document.getElementById('txt').innerHTML=c;
Finally, you might want timedCount() to stopCount() if c goes below zero. This is easy enough:
if (c <= 0) stopCount();
Related
I am currently studying Javascript and came across a problem while practising setInterval() and `clearInterval().
I am writing a timer that will stop as soon as I press on a button. I have a variable in which I start the interval, a function that executes the timer code and writes the current number the timer is on into a div in HTML.
Then I have a getElementById call that writes an onclick into a button with an id of theButton which contains a clearInterval.
The problem is, if I just write the clearInterval right in the end of the code, without an onclick, it works. But as soon as I write it inside an onclick, it doesn't work without even showing a error.
I have tried searching on the internet and the only answer I got was to use a var instead of a let for the variable with the interval, but that didn't work.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
}
}
document.getElementById("theButton").onclick = 'clearInterval(timerVariable)';
The main reason it doesn't work is because you should assign a function reference to onclick, not a string. Your code should look something like this:
document.getElementById("theButton").onclick = function() {
clearInterval(timerVariable);
});
However, taking this a step further, the onclick is no longer considered good practice. A better solution is to attach your events using addEventListener(), like this:
document.querySelector('#theButton').addEventListener('click', () => {
clearInterval(timerVariable);
});
Here's a full working version with the above correction applied. Note that I added an else case to also clear the interval when the count reaches 0. Without this the interval will run infinitely without any purpose.
var timerVariable = setInterval(theTimer, 1000);
let count = 11;
function theTimer() {
if (count != 0) {
count--;
document.querySelector("div").innerHTML += count;
console.log("its working");
} else {
clearInterval(timerVariable);
}
}
document.querySelector("#theButton").addEventListener('click', () => {
clearInterval(timerVariable);
});
<button type="button" id="theButton">Stop</button>
<div></div>
I'm trying to put in a small easter egg on a site I'm building where if a user clicks a link x amount of times it will trigger a popup, I'd guess this would be some kind of JS or JQuery but I have no idea where to start or if it's even possible. I guess what I really want is something like the easter egg built into the Android 'About Phone' page, which opens a new page after about 7 clicks within 5 seconds. Is there any way to do this in a browser?
Maybe an OnClick command which adds 1 to a counter and does an action when the counter reaches a specified number, but resets the counter to 0 every 10 seconds? (I don't want to make it too easy to find!)
Thanks
Try this one with jQuery:
Html:
<a id='lnkEgg' data-clicks='0'>Click for surprise</a>
Script:
$(function(){
$("#lnkEgg").on("click",function(){
var c=$(this).data("click");
if(c==7){
//if it equals to whatever number you are chasing
//open the popup
}else{
$(this).data("clicks",c++);
}
});
});
Use a setTimeout (which you clear each time) and preventDefault on the click event if it doesn't meet your requirements.
(function (node) { // IIFE to keep our namespace clean :)
var timer,
count = 0;
function timeup() {
count = 0;
}
function handler(e) {
clearTimeout(timer);
timer = setTimeout(timeup, 5e3); // 5 seconds
++count;
if (count < 7) // number of clicks
e.preventDefault();
}
node.addEventLister('click', handler);
}(document.getElementById('myLink'))); // passing the <a> into the IIFE
This code must be run after the target element exists
#TheVillageIdiot's technique is the way to go. Here I'll just show some approach using the same technique:
$(function(){
var egg = $('#lnkEgg');
egg.on('click', function() {
//increment and check if magic clicks has been reached
if( ++$(this).data().clicks == 7 ) {
console.log( "You've now clicked the required number of times");
//do some more operations
$(this).data('complete', true);
console.log( $(this).data() );
};
});
//Reset counter every 10 seconds
setInterval(function() {
egg.data().clicks = 0;
}, 10000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a id="lnkEgg" data-clicks="0">Click for surprise</a>
I used
<div id="myJSDiv"><script>...</script></div>
$("#myJSDiv").html('');
and
<script id="myJSDiv">...</script>
$("#myJSDiv").remove();
but nothing removed.
JS script is
<script id="count_down">
var ss = 150;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="google.com";
}else {
document.getElementById("countdown").innerHTML=ss;
window.setTimeout("countdown()", 1000);
}
}
</script>
Once a script has loaded, removing the script tag it came from does not do anything to the functions or variables defined or created by that script.
There is no way to remove a block of code like that after it has loaded. Global functions can be redefined after they were loaded, but that's about all you can do. Perhaps, if you described the overall problem you are trying to solve, we could suggest a better approach.
Now that you've added the actual problem to your question, to stop your countdown timer, you can do this:
<script id="count_down">
var ss = 150;
var countdownTimer;
function countdown() {
ss = ss-1;
if (ss<0) {
window.location="google.com";
}else {
document.getElementById("countdown").innerHTML=ss;
countdownTimer = window.setTimeout(countdown, 1000);
}
}
function stopCountdown() {
clearTimeout(countdownTimer);
}
</script>
Just call the stopCountdown() function when you want to stop the countdown timer.
This is the slideshow script, I want it to stop when mouse move over. But i dont know what to add on it. I've tried to look for it online, but all of them doesn't work:(
<SCRIPT LANGUAGE="JavaScript">
<!--
var dimages=new Array();
var numImages=2;
for (i=0; i<numImages; i++)
{
dimages[i]=new Image();
dimages[i].src="/v/vspfiles/assets/images/image"+(i+1)+".jpg";
}
var curImage=-1;
function swapPicture()
{
if (document.images)
{
var nextImage=curImage+1;
if (nextImage>=numImages)
nextImage=0;
if (dimages[nextImage] && dimages[nextImage].complete)
{
var target=0;
if (document.images.myImage)
target=document.images.myImage;
if (document.all && document.getElementById("myImage"))
target=document.getElementById("myImage");
if (target)
{
target.src=dimages[nextImage].src;
curImage=nextImage;
}
setTimeout("swapPicture()", 4000);
}
else
{
setTimeout("swapPicture()", 1000);
}
setTimeout("swapPicture()", 4000);
//-->
Based on the info provided ( only the javascript at this point ). The slideshow script is dependent on
setTimeout();
The code responsible for stopping setTimeout(); is
clearTimeout();
Add the mouse event(s) to the slideshow and call clearTimeout(). As for the mouse events and best practices check SO for more instructions.
Here is one reference about setTimeout().
http://www.w3schools.com/js/js_timing.asp
Please post HTML for better and more accurate code on the mouse events.
I have that Javascript counter:
var x=100;
function timerCountdown()
{
document.getElementById('timer1').value=x;
x--;
t=setTimeout("timerCountdown()",1000);
if (x<-1)
{
document.getElementById('timer1').value='Done!';
clearTimeout(t);
}
}
function stopCounter(){
clearTimeout(t);
x=x+1;
}
Then I use:
<body onFocus='timerCountdown()' onBlur='stopCounter()'>
But the problem is, the countdown doesn't start when the page loads. It waits for me to click on another window and to reFocus on the window again.
So I tried this:
<body onLoad='timerCountdown()' onFocus='timerCountdown()' onBlur='stopCounter()'>
But this time, the countdown goes pretty fast. Probably because timerCOuntdown is called twice every second.
Alternatively, I could just use the onFocus and onBlur in the body tag, but I need a function to trigger the Focus upon body load. Is that possible?
Does anyone have a suggestion to solve this problem?
thanks a lot!
The simple answer is because setTimeout is invoked twice, running timerCountdown() once for two times separately, and continually setting two setTimeout IDs.
This would be what you want:
var x = 100;
var t = 0;
function timerCountdown()
{
if (t == 0) t = setInterval(timerCountdown, 1000);
document.getElementById('timer1').value=x;
x--;
if (x < 0)
{
document.getElementById('timer1').value='Done!';
clearTimeout(t);
ticker = 0;
}
}
function stopCounter()
{
clearTimeout(t);
t = 0;
x++;
}
setInterval is much more suited for countdown timers, and things you need to run continually since setTimeout only runs once and you need to keep on calling it.
Edit: This fixes the initial rapid triggering of the timer on Firefox.
Remove the handler from <body onload= and add this to the end of the script block above:
t = setInterval(timerCountdown, 1000);