i wrote a function which do count down or up the numbers to another by pressing a button.
look at this :
var timer;
function counterFn(element,oldCount,newCount,speed) {
if(isNaN(speed)) speed=100;
clearInterval(timer);
if(oldCount===newCount) {
element.text(newCount);
return;
}
var counter=oldCount;
timer=setInterval(function() {
if(oldCount<newCount) {
if(counter>newCount)
clearInterval(timer);
counter++;
} else {
if(counter<newCount)
clearInterval(timer);
counter--;
}
if(counter===newCount) {
clearInterval(timer);
}
element.text(counter);
},speed);
}
$('.button').on("click",function() {
counterFn('.endelement',10,100,1);
});
description of the function attributes:
element : the element which will show the result
oldCount : is the start number
newCount : is the end number
speed : is the repeat time of setInterval
now, according to above code, if you press the element with .button class, counterFn function will run. now if you press the button again (before clearing the setinterval by the function), every thing is OK.
this is the working demo : http://jsfiddle.net/hgh2hgh/gpvn9hcq/4/
as you can see, clicking on the button, clear the previous interval and run the new one.
now if the second element call that function like this :
$('.button2').on("click",function() {
counterFn('.endelement2',50,70,2);
});
naturally the second request will stop the timer and run new timer with the new attributes. cause a global variable is defined for just one setInterval.
look at the comments for demolink of this part : [1] in comments
if definition of the variable be inside the function, pressing the button twice, mean running the function for two separate time.
look at the comments for demolink of this part : [2] in comments
OK, now how to run this function correct?
thanks.
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>
My objective is to keep a user in a view as long as he/she keeps clicking a button within a certain lapse.
I'm using Rails and was exploring a solution via an embedded JS in the pertinent view.
So far I'm able to set a time after which the user will be redirected to root path with the following script:
var delayedRedirect = function (){
window.location = "/";
}
var delay = 10000;
$(document).ready(function() {
setTimeout('delayedRedirect()', delay);
});
I've been trying to write a function that resets the value of 'delay'or that calls the setTimeoutFunction again.
$('#btn-persist').click(function() {
delay = 3000;
// or calling again setTimeout('delayedRedirect()', delay);
});
But I noticed that changing the variable won't affect the setTimeout function that has already been called.
I've also tried to use the clearTimeout function as below without success
var delayedRedirect = function (){
window.location = "/persists";
}
var delay = 3000;
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
var stopRedirect = function (){
clearTimeout(triggerRedirect);
}
$(document).ready(function() {
triggerRedirect();
$('#btn-persist').click(function() {
stopRedirect();
});
});
I wonder why this may not be working and if there's any other way to stop the execution of the setTimeout function that has already been called so I can call it again to effectively reset the time to the original value of 'delay'.
At the same time, I don't want to stop any other JS functions that are running in parallel.
Do you see a better solution to achieve this?
The main problem why clearTimeout is not working. because you are clearing a anonymous function instead of a setTimeout variable
change this
var triggerRedirect = function() { setTimeout('delayedRedirect()', delay);
}
to this
var triggerRedirect = setTimeout('delayedRedirect()', delay);
Edit:
also change this (if you want to restart the inactive redirect trigger)
$('#btn-persist').click(function() {
stopRedirect();
});
to this
$('#btn-persist').click(function() {
stopRedirect();
triggerRedirect();
});
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'm looking for another way to execute this code :
$.each($("#gallery > img"), function(index,curImg) {
setTimeout(function() {
clearCanvas();
cvsCtx.drawImage(curImg,0,0);
} , index*animationMs);
});
This code draw an image from my gallery to my canvas every animationMs .
But i would like to make it possible to stop the animation, with a "Play/stop" button, I can't do it this way...
Any idea or workaround ?? thank you !!
I can't test it. But you can stop animation by using a variable to hold the setTimeout function as following:
var x; // public var
....
x = setTimeout(......);
// To stop it use:
clearTimeout(x);
Hope this works for you
I find that creating timeouts in a loop is usually too hard to manage - you don't want to have to cancel multiple timeouts. Better to have the function doing the work call itself (indirectly) by setting a timeout just before it completes, because then you can put in a simple if test to decide whether to set the next timeout and continue your animation.
Perhaps a little something like this:
<input id="playPause" type="button" value="Play">
<script>
function initAnimation(animationMs, autoRepeat, waitForPlayButton) {
var currentFrame = 0,
$imgList = $("#gallery > img"),
paused = waitForPlayButton;
function drawNext() {
clearCanvas();
cvsCtx.drawImage($imgList[currentFrame++],0,0);
if (currentFrame >= $imgList.length) {
currentFrame = 0;
if (!autoRepeat) {
paused = true;
$("playPause").prop("value", "Play");
}
}
if (!paused)
setTimeout(drawNext, animationMs);
}
$("playPause").prop("value", waitForPlayButton ? "Play" : "Pause")
.click(function() {
this.value = (paused = !paused) ? "Play" : "Pause";
if (!paused)
drawNext();
});
if (!waitForPlayButton)
drawNext();
}
initAnimation(100, true, false);
</script>
If autoRepeat param is false the animation will run once and stop, but can be restarted via the button, otherwise (obviously) it just keeps repeating.
If waitForPlayButton is false the animation will start immediately, otherwise (obviously) it will start when the button is pressed.
Pressing the button will pause at the current frame.
(Not tested since I don't have a bunch of images handy, but I'm sure you get the idea and can fix any problems yourself. Or let me know if you get errors...)
var images = $("#gallery > img").clone(), interval;
function startLoop() {
interval = setInterval(function(){
var image = images[0];
clearCanvas();
cvsCtx.drawImage(image,0,0);
images.append(image);
}, animationMs);
}
$(".stop").click(function() {clearInterval(interval);});
$(".start").click(startLoop);
setTimeout return a timeoutID which can be given to clearTimeout as a parameter to stop the timeout from happening.
You can read more about this at: https://developer.mozilla.org/en/DOM/window.setTimeout
Good luck
It's not really an animation... but still:
$("#gallery > img").each(function(index,curImg) {
$(this).delay(index*animationMs).queue(function(next) {
clearCanvas();
cvsCtx.drawImage(curImg,0,0);
if (next) next();
});
});
Using jQuery queues like I did allows you to do .stop(true), on $("#gallery > img") or a single image and stop their "animation".
First you could add images to a javascript array variable (eventually global) and then call a function cycle() on that array for all its length.
You should put your setTimeout() call inside that function, assigning it to a variable: var t=setTimeout("cycle()",animationMs); and execute clearTimeout(t); when you want to stop the animation.
Of course you could also save in a variable the frame where you were when stopping the animation and restart exactly from that frame when pressing "play" button.
I'm designing a web site and I would like to be able to call a function 1 second after the last user input. I tried using onKeyUp, but it waited 1 second after the first keystroke.
Does anyone know how would this be possible?
Another similar approach, without globals:
var typewatch = function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
}
}();
...
<input type="text" onKeyUp="typewatch(function(){alert('Time elapsed!');}, 1000 );" />
You can this snippet here.
You can use a keyDown (or keyUp) event that sets a function to run in 1 second and if the user types another key within that second, you can clear the timeout and set a new one.
E.g.
var t;
function keyDown()
{
if ( t )
{
clearTimeout( t );
t = setTimeout( myCallback, 1000 );
}
else
{
t = setTimeout( myCallback, 1000 );
}
}
function myCallback()
{
alert("It's been 1 second since you typed something");
}
Nevermind, I found a way to do it. I call a function on each onkeyup() which increment a counter and then wait 1 second. After the 1 second elapsed, it decrement the counter and check if it's equal to 0.
var keystrokes = 0;
function askAgain()
{
++keystrokes;
setTimeout(reveal, 1000);
}
function reveal()
{
--keystrokes;
if (keystrokes == 0)
alert("Watch out, there is a snake!");
}
Just modify your html input and toss that first line into your existing functions so you're not having to recode anything you have. It will not affect any old code-calling functions either, since if onkeypress is not set then mykeypress will always be < 1.
var mykeypress=0;
var mysleep=1000; //set this higher if your users are slow typers
function mytest(id,text) {
mykeypress--; if(mykeypress > 0) { return; }
//anything you want when user stops typing here
alert("Keypress count at "+mykeypress+" ready to continue
id is "+id+" arguement is "+text);
}
input type="text" name="blah" id="55" onkeypress="mykeypress++"
onkeyup="myid=this.id;setTimeout(function (){mytest(myid,'a test')},mysleep)"
REVERT to old way seamlessly:
input type="text" name="blah" id="55" onkeyup="mytest(this.id,'a test')"
There is some simple plugin I've made that does exacly that. It requires much less code than some proposed solutions and it's very light (~0,6kb)
First you create Bid object than can be bumped anytime. Every bump will delay firing Bid callback for next given ammount of time.
var searchBid = new Bid(function(inputValue){
//your action when user will stop writing for 200ms.
yourSpecialAction(inputValue);
}, 200); //we set delay time of every bump to 200ms
When Bid object is ready, we need to bump it somehow. Let's attach bumping to keyup event.
$("input").keyup(function(){
searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback
});
What happens here is:
Everytime user presses key, bid is 'delayed' (bumped) for next 200ms. If 200ms will pass without beeing 'bumped' again, callback will be fired.
Also, you've got 2 additional functions for stopping bid (if user pressed esc or clicked outside input for example) and for finishing and firing callback immediately (for example when user press enter key):
searchBid.stop();
searchBid.finish(valueToPass);
// Get the input box
let input = document.getElementById('my-input');
// Init a timeout variable to be used below
let timeout = null;
// Listen for keystroke events
input.addEventListener('keyup', function (e) {
// Clear the timeout if it has already been set.
// This will prevent the previous task from executing
// if it has been less than <MILLISECONDS>
clearTimeout(timeout);
// Make a new timeout set to go off in 1000ms (1 second)
timeout = setTimeout(function () {
console.log('Input Value:', input.value);
}, 1000);
});
<!-- a simple input box -->
<input type="text" id="my-input" />
Credits to:
Wait for User to Stop Typing, in JavaScript