How would you create a "typing" effect using jQuery? - javascript

I'm trying to make a jQuery function that spells my name out letter by letter. My name is Jake, so I want it to start out with nothing, then it'll display a J, then Ja, then Jak, then Jake. Let's just say that I'm modifying a paragraph element with class name:
<p class=Name> *name gets 'typed' here* </p>
I've tried using the .delay() function and the setTimeout() function, but I'm new to jQuery so I'm probably using them wrong.
$(document).ready(function()
{
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 500);
setTimeout(function(){$(".name").text('Jak');}, 500);
setTimeout(function(){$(".name").text('Jake');}, 500);
});
Here is a jfiddle of my most recent attempt:
http://jsfiddle.net/pg7Cu/
This just delays for 500 milliseconds then types my name all at once. I'm trying to get it to type one letter every 500 milliseconds. Can someone help me figure out how to do this?

Simply use a recursive function:
var name = "Jake";
function typeName(name, iteration) {
// Prevent our code executing if there are no letters left
if (iteration === name.length)
return;
setTimeout(function() {
// Set the name to the current text + the next character
// whilst incrementing the iteration variable
$('.name').text( $('.name').text() + name[iteration++] );
// Re-trigger our function
typeName(name, iteration);
}, 500);
}
// Call the function to begin the typing process
typeName(name, 0);
JSFiddle demo.
We can extend this slightly to remove the need for initially passing in the iteration variable by adding this as the first line in our typeName function:
var iteration = iteration || 0;
Now you can simply call:
typeName("My name here");
JSFiddle demo.

Actually You can do it also with css only, No need of javascript/jQuery.
HTML
<p class="text">Jack.</p>
CSS
.text
{
width: 30em;
white-space:nowrap;
overflow:hidden;
-webkit-animation: type 5s steps(50, end);
animation: type 5s steps(50, end);
}
#keyframes type{
from { width: 0; }
}
#-webkit-keyframes type{
from { width: 0; }
}
Demo

Here is a simple one:
http://jsfiddle.net/pg7Cu/7/
var text = "Hello what's up?";
function letter() {
var oldt = $(".name").text(); // grab old text
var t = text.charAt(0); // grab first text's letter
text = text.substr(1); // shorten the text
$(".name").text(oldt + t); // show old text + the one letter
// if there's anything left to type, continue.
if(text.length > 0) setTimeout(letter, 100);
}
$(document).ready(function()
{
setTimeout(letter, 100);
});
It sets a timeout for a letter, and when the letter is shown, if there is more, it sets the timeout again. Sort of recursion.

You're close. Start by incrementing the timeouts; as the timer starts running immediately:
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 1000);
// etc
And don't set the differences in time exactly the same (as people don't hit a key every x ms constantly)
Check out a revised version: http://jsfiddle.net/pg7Cu/1/
And you could create more beautiful code etc. etc. but this works.
EDIT
Ok I took the challenge ;) Check out this Fiddle. You can call the function simulateTyping() with your own string, and at random intervals it will append the next character, until the whole string is on the screen. You could even create a plugin from it (by NOT hard-coding the element the text should be appended to).
function simulateTyping(myString, currentChar) {
var delay = Math.floor(Math.random()*(250-50+1)+50); // random between 50 and 250 milliseconds
currentChar = currentChar || 0;
setTimeout(function() {
$('.name').append(myString.charAt(currentChar))
if(++currentChar < myString.length) {
simulateTyping(myString, currentChar);
}
}, delay);
}

You can try with different timeouts:
setTimeout(function(){$(".name").text('J');}, 500);
setTimeout(function(){$(".name").text('Ja');}, 1000);
setTimeout(function(){$(".name").text('Jak');}, 1500);
setTimeout(function(){$(".name").text('Jake');}, 2000);

Related

Stop after last slide [duplicate]

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

Cancel a function if button is clicked [duplicate]

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

Letter by letter animation with delay in loading

I'm trying to implement letter by letter animation on section with two slides. Currently I'm using jQuery code for that, but I'm afraid it's far from the ideal option.
Here's my code example: codepen
$.fn.animation = function () {
//get the welcome msg element
var $message = $(this);
//get a list of letters from the welcome text
var $getList = $(this).text().split("");
//clear the welcome text msg
$(this).text("");
//loop through the letters in the list array
$.each($getList, function(idx, element) {
//create a span for the letter and set opacity to 0
var newElement = $("<span/>").text(element).css({
opacity: 0
});
//append it to the welcome message
newElement.appendTo($message);
//set the delay on the animation for this element
newElement.delay(idx * 90);
//animate the opacity back to full 1
newElement.animate({
opacity: 1
}, 1100);
});
};
$('.introduction').animation();
$('.secondary').animation();
First problem is that I can't do, so the second sentence with class "secondary" runs only after first one is finished. I've tried to use .delay and setTimeout, but that doesn't help.
Also I'm not sure, how to start animation on second slide, when it's loaded.
I know there's plugins for that stuff, but I'd like to do that in vanilla JavaScript, or jQuery, css3.
Would be glad for any help.
And yeah, here's an example how I would like it to look - http://bootstrapart.net/influence/v1.5.3/
Is it possible to make, so the animation starts every time, when slide is changed?
Thanks.
Edited
Click here to see the whole code working.
Changes I made in css: I set the opacity of html text tags (<h1>,<h3> and <h4>) to 0, so they are hidden. Then in the animation function they are made visible again.
Changes I made in script: To start the second text animation with delay I used setTimeout() function:
setTimeout(function(){
$('.secondary').animation();
},2000);
To detect the slide event of carousel, according to Bootstrap Documentation you can use this method:
$('.carousel').on('slid.bs.carousel', function () {
// here is where you start the animation for the second slide
})
Re-Edit
To track on which slide we are I introduced a variable caled: var $wichSlide. Here is the working method to start the animation when slide is changed:
$('.carousel').bind('slid.bs.carousel', function (e) {
if($whichSlide == 1){
//set $whichSlide position for the next slide event
$whichSlide = 2
//start to animate the text
$('.introduction').animation();
setTimeout(function(){
$('.secondary').animation();
},2000);
/*set the text on the second slide to be invisible
* because we don't want it to appear before animation starts
*/
$('.slide2').css("opacity",0);
}else if($whichSlide == 2){
$whichSlide = 1;
$(".carousel").carousel("pause");
$(".slide2").animation();
setTimeout(function(){
$(".carousel").carousel();
},3000);
$('.introduction').css("opacity",0);
$('.secondary').css("opacity",0);
}
});
See the working code

How to make my script loop

I created an image slider that ends on one image, but now I'd like to take it a step further and make it loop.
Here is my code in the head tag
<style>
#picOne, #picTwo, #picThree, #picFour, #picFive{
position:absolute;
display: none;
}
#pics {
width:500px;
height:332px;
}
</style>
<script src="http://code.jquery.com/jquery-1.4.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#picOne').fadeIn(1500).delay(3500).fadeOut(1500);
$('#picTwo').delay(5000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picThree').delay(10000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFour').delay(15000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFive').delay(20000).fadeIn(1500).delay(3500);
});
</script>
and here is where it is implemented in the body code
<div id="pics">
<center>
<img src="img/dolllay.jpg" width="500" height="332" id="picFive" />
<img src="img/dye.jpg" width="500" height="332" id="picTwo" />
<img src="img/dollsit.jpg" width="500" height="332" id="picThree" />
<img src="img/heirloom.jpg" width="500" height="332" id="picFour" />
<img src="img/heritage.jpg" width="500" height="332" id="picOne" />
</center>
</div>
Could I turn it into a function and then loop it? Can I get any guidance on that? Thank you very much
Everyone's answering the question, but not solving the problem.
Sure, you can just put a loop wrapper around it (preferably one that doesn't terminate), but why not just program it right? Why have all the hardcoded times, and why not make it more robust?
Try rewriting your code like this. It makes it much easier to modify the pictures you loop through:
var pictures = ["picOne", "picTwo", "picThree", "picFour", "picFive"];
var index = 0;
var displayImage = function() {
if (index == pictures.length) { return; }
$("#" + pictures[index++]).fadeIn(1500).delay(3500).fadeOut(1500, displayImage);
};
displayImage();
Then, if you want to loop back, you simply tweak the displayImage function:
var displayImage = function() {
if (index == pictures.length) { index = 0; }
$("#" + pictures[index++]).fadeIn(1500).delay(3500).fadeOut(1500, displayImage);
};
TRY IT at jsfiddle
EDIT
On more careful reading of your question, I see that my original answer didn't do exactly what you needed. You have it set so that every five seconds, one will have faded out and the other one will have faded in. Currently, mine takes 6.5 seconds, since mine is all operating sequentially instead of concurrently. To make it come close to matching yours, just change the 1500s to 750s:
$("#" + pictures[index++]).fadeIn(750).delay(3500).fadeOut(750, displayImage);
This will take the right amount of time. It's slightly different from yours, in that one fades out all the way before the other fades in. The alternative is to actually skip the fadeIn and keep the fadeout. This is a lot closer to the way yours looks.
$("#" + pictures[index++]).show().delay(3500).fadeOut(1500, displayImage);
Or, make a very small fadein, to help reduce the flash of the new image:
$("#" + pictures[index++]).fadeIn(100).delay(3500).fadeOut(1400, displayImage);
Final Edit (really!)
Ok, to get the fadeIn and fadeOut to work reliably at the same time, the solution was to use neither. I went back to using animate, instead. As a result, I had to completely rewrite the displayImage function, but this is exactly what you need:
var displayImage = function () {
if (index == pictures.length) {
index = 0;
}
$("#" + pictures[index]).show().delay(3500).animate({
opacity: 0.2
}, {
step: function (now) {
var idx = (index + 1) % pictures.length;
var val = 1.2 - now;
$("#" + pictures[idx]).show().css("opacity", val);
},
complete: function () {
$("#" + pictures[index++]).hide();
displayImage();
}
});
};
What this does is move the sequence to "show->fadeIn and Out" instead of "fade in -> show -> fade out". To make your transition smooth, I only fade it out to 0.2 instead of 0. The step function is what fades the other one in at the same time. Once the new pic is visible, I completely hide the old pic.
Here's the working fiddle for it.
$(document).ready(function() {
setInterval(example, 10000); // repeat every 10 seconds
});
function example() {
$('#picOne').fadeIn(1500).delay(3500).fadeOut(1500);
$('#picTwo').delay(5000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picThree').delay(10000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFour').delay(15000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFive').delay(20000).fadeIn(1500).delay(3500);
}
A better way would be to give each pic the same class such as 'fadeinout'. This will mean you don't have to re-write your code when you add/remove more pics.
eg
<img id="picFive" class="fadeinout" ....
/* not sure if they are even <img>s but whatever they are*/
Then do
$(document).ready(function() {
beginFades();
});
function beginFades() {
$('.fadeinout').each( function(i,el) { // find all elements with fadeinout
//for each one, trigger the start of the fading after i*5000 milliseconds
//i is the index of the element as it was found by jQuery - this will be in
//document order (which actually may not be what you have but I'm guessing
//it is)
setTimeout(function(){
makeImgFadeInOut($(el))
}, i*5000);
});
}
function makeImgFadeInOut(el) {
//trigger a single fadeIn, fadeOut.
//But add a callback function to the end of fadeOut which retriggers the whole
//thing
el.fadeIn(1500).delay(3500).fadeOut(1500, function(){makeImgFadeInOut(el);});
}
WORKING DEMO (WITH DIVS)
You can use setInterval to loop it forever, or setTimeout to loop it for a specific duration.
<script type="text/javascript">
$(document).ready(function() {
setInterval(ImageSlider, 1000);
});
function ImageSlider() {
$('#picOne').fadeIn(1500).delay(3500).fadeOut(1500);
$('#picTwo').delay(5000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picThree').delay(10000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFour').delay(15000).fadeIn(1500).delay(3500).fadeOut(1500);
$('#picFive').delay(20000).fadeIn(1500).delay(3500);
}
</script>
If you want to have total control upon your elements you can use this:
var elements = [{
el: '#pic1',
delay: 3500,
fadeIn: 1500,
fadeOut: 1500
},
{
el: '#pic2',
delay: 3500,
fadeIn: 1500,
fadeOut: 1500
}
//... other elements
]
var index = null;
(function loop(){
index = index || 0;
index = index % elements.length();
$(elements[index].el).fadeIn(elements[index].fadeIn, function(){
$(this).delay(elements[index].delay)
.fadeOut(elements[index].fadeOut, function(){
index++;
window.setTimeout(loop, 5000);
});
})();
Edit : forgot to execute the first iteration of the loop function and removing the useless call for index inside the loop
The good thing about how this loop works is that it doesn't use the SetInterval function.
and the code inside the loop need to finish what it does inside before iterating again.
(you won't have this hideous bug if you click an other tab and go back to your carousel)
#ElRoconno answer is pretty good too if you require less configuration
Use any of this-
setInterval() - executes a function, over and over again, at specified time intervals
setInterval(function(){alert("Hello")},3000);
setTimeout() - executes a function, once, after waiting a specified number of milliseconds.
setTimeout(function(){alert("Hello")},3000);
What is the difference between both setInterval and setTimeout
for you may be the setTimeout will not work as it will run only once after a delay and setInterval will go on to make continuous repetitive call until the window.clearInterval(intervalVariable) is been called
I have created an example on jsfiddler here. Basically you don't have to do this one at a time. Just get the whole collection of images as an array and loop over them. Hope this helps
$(document).ready(function () {
var arr = $('.pics')
arr.hide();
$(arr[0]).fadeIn(1500).delay(3500).fadeOut(1500);
var index = 1;
var maxIndex = arr.length - 1;
setInterval(function () {
/*arr.hide();
var pic = $(arr[index]);
pic.show();
*/
var pic = $(arr[index]);
pic.fadeIn(1500).delay(3500).fadeOut(1500);
index++;
if (index >= maxIndex) {
index = 0;
}
}, 6500);
});
There's really no need for setInterval here since you can use the callback built-into .fadeOut(), nor having to enumerate an array of images. You can do something as simple as:
var idx = 0;
fade();
function fade() {
if (idx >= $('img').length) idx = 0;
$('img').eq(idx).fadeIn(1500).delay(3500).fadeOut(1500, fade);
idx++;
}
jsFiddle example

Stop setInterval call in JavaScript

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.

Categories