Making text blink a certain number of times? - javascript

I'm trying to make this blinking text stop after 3 seconds (or 3-5 blinks). I've set the blink rate to about the right speed, but cannot figure out how to make it stop.
Here's the code:
$('.blink').each(function() {
var elem = $(this);
setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
} else {
elem.css('visibility', 'hidden');
}
}, 200);
});
Any suggestions?
I've compiled a jQuery fiddle here: http://jsfiddle.net/M4Fcd/173/

setInterval goes on indefinitely - or until stopped.
What you need to do is capture the intervalID when you create the interval and then clear the interval after you are done with it
var intervalID = setInterval(function....);
// when done
clearInterval(intervalID);
In your particular case:
$('.blink').each(function() {
var elem = $(this);
// count the blinks
var count = 1;
var intervalId = setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
// increment counter when showing to count # of blinks and stop when visible
if (count++ === 3) {
clearInterval(intervalId);
}
} else {
elem.css('visibility', 'hidden');
}
}, 200);
});
Updated fiddle http://jsfiddle.net/M4Fcd/186/

You could also use fadeIn/fadeOut like this
$('.blink').each(function() {
var elem = $(this);
elem.fadeOut(100)
.fadeIn(100)
.fadeOut(100)
.fadeIn(100)
.fadeOut(100)
.fadeIn(100);
});
jsFiddle

$('.blink').each(function() {
var elem = $(this);
refreshIntervalId = setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
} else {
elem.css('visibility', 'hidden');
}
}, 200);
});
setTimeout(function(){
clearInterval(refreshIntervalId);
}, 3000)
fiddle: http://jsfiddle.net/M4Fcd/176/

try this:
var i = 0;
var blink;
$('.blink').each(function() {
var elem = $(this);
blink = setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
i++;
if(i >= 3){
clearInterval(blink);
}
} else {
elem.css('visibility', 'hidden');
}
}, 200);
});
Fiddle

Ok, there is better way. You can just toggle css class with visibility: hidden, the code gets simpler and than if you want to stop when visible/not visible just need to check with hasClass.
$('.blink').each(function() {
var elem = $(this),
timer = 0,
interval = 200,
stopAfter = 3000,
intervalId = setInterval(function() {
elem.toggleClass('blink');
if(timer > stopAfter && !elem.hasClass('blink')) {
clearInterval(intervalId);
}
timer += interval;
}, interval);
});
fiddle: http://jsfiddle.net/M4Fcd/183/
Now you can stop it when it's visible or not, but the idea is pretty the same.
$('.blink').each(function() {
var elem = $(this),
timer = 0,
interval = 200,
stopAfter = 3000;
refreshIntervalId = setInterval(function() {
if (elem.css('visibility') == 'hidden') {
elem.css('visibility', 'visible');
if(timer > stopAfter) {
clearInterval(refreshIntervalId);
}
} else {
elem.css('visibility', 'hidden');
}
timer += interval;
}, interval);
});
fiddle: http://jsfiddle.net/M4Fcd/180/

I think I have the shortest answer.
function blinkElement(elm, interval, duration) {
elm.style.visibility = (elm.style.visibility === "hidden" ? "visible" : "hidden");
if (duration > 0) {
setTimeout(blinkElement, interval, elm, interval, duration - interval);
} else {
elm.style.visibility = "visible";
}
}
To blink for 3 seconds in the rate of 200 milliseconds.
blinkElement(element, 200, 3000);

Related

Reset JS timer when window goes out of focus

Been twisting my head for a long time over this and can't seem to get it to work.
Basically trying to reset the timer when the window goes out of focus for longer than 30 seconds.
I'd be thankful for any solution that works.
Regards, Will.
window.onData = function(data) {
if (data.setDisplay == true) {
$("#container").css('display', 'flex');
$("body").fadeIn(1000);
var counter = 90;
var c = 90;
var i = setInterval(function(){
$(".loading-page .counter h1").html("YOU HAVE " + c + " SECONDS LEFT UNTIL RESPAWN");
$(".loading-page .counter hr").css("width", c + "");
counter--;
c--;
if(counter == 0) {
$(".loading-page .counter h1").html("YOU MAY DO /RESPAWN");
$(".loading-page .counter p").html("DON'T FORGET THE NEW LIFE RULE!");
clearInterval(i);
}
}, 1000);
} else {
$("#container").css('display', 'none');
$("body").css('display', 'none');
}
}
window.onload = function(e) {
window.addEventListener('message', function(event) {
onData(event.data)
});
}
Perhaps you mean this?
Not tested but has enough snippets to be moved around
const onData = function(data) {
if (data.setDisplay == true) {
$("#container").css('display', 'flex');
$("body").fadeIn(1000);
let tId = setInterval(function() {
$(".loading-page .counter h1").html("YOU HAVE " + counter + " SECONDS LEFT UNTIL RESPAWN");
$(".loading-page .counter hr").css("width", counter);
counter--;
if (counter == 0) {
$(".loading-page .counter h1").html("YOU MAY DO /RESPAWN");
$(".loading-page .counter p").html("DON'T FORGET THE NEW LIFE RULE!");
clearInterval(tId);
}
localStorage.setItem("counter",counter);
}, 1000);
} else {
$("#container").hide()
$("body").hide()
}
}
let counter;
const getCounter = function() {
counter = localStorage.getItem("counter");
counter = counter === null ? 90 : +counter; // continue from where it was
const now = new Date().getTime()
const blurred = sessionStorage.getItem("blurred");
blurred = blurred ? +blurred : 0;
if (blurred && (now-blurred)/1000) >30) counter = 0;
};
$(function() {
$(window).on('message', function(event) {
onData(event.data)
});
$(window).on("blur",function() {
sessionStorage.setItem("blurred",new Date().getTime())
})
});
$(window).on("focus",getCounter )

setInterval on resize

I have the below code:
var intervalId = "";
var isRunning = false;
var iCount = 0;
function animation() {
switch (iCount++ % 2) {
case 0:
$('.class1').removeClass("is-active");
$(".class2").addClass("is-active");
break;
case 1:
$('.class2').removeClass("is-active");
$(".class1").addClass("is-active");
break;
}
isRunning = true;
}
if (window.innerWidth > 1024) {
intervalId = setInterval(animation, 3000);
}
$(window).on("orientationchange resize", function () {
debounce(function () {
if (window.innerWidth < 1024) {
if (isRunning == true) {
clearInterval(intervalId);
isRunning = false;
}
} else if (window.innerWidth > 1024) {
if (isRunning == false) {
intervalId = setInterval(animation, 3000);
}
}
}, 250);
});
What I'm trying to get, is on a 1024+ screen the setInterval is fired, anything below 1024 isn't fired. But on resize to lower than 1024 the setInterval still being fired.
Any help would be greatly appreciated.
The isRunning logic is useless and redundant with intervalId being defined or not. You're using two variables for the same thing, and that's overkill.
Besides, you test window.innerWidth twice : is it <1024 or is it >1024 ? The second test is useless, and what happens if it's exactly 1024?
This block code makes things clearer and simpler :
debounce(function () {
if (window.innerWidth < 1024) {
clearInterval(intervalId);
} else {
if(!intervalId) intervalId = setInterval(animation, 3000);
}
})
I got it working by using this code for my resize function.
$(window).on("orientationchange resize", debounce(function () {
if (window.innerWidth < 1024) {
clearInterval(intervalId);
intervalId = "";
} else {
if (!intervalId) intervalId = setInterval(animation, 3000);
}
}));

Time to start only after button click

http://jsfiddle.net/Bwdfw/98/
is there a way to start timer only after a button is clicked in the given jsfiddle link
http://jsfiddle.net/Bwdfw/98/
var seconds=0;
var Score=0;
var index=0;
countdown(60);
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
Have a function inside the click handler and a variable which states if the function has started or not.
Also you can club the click events inside a single handler and the index can be stored as part of the data-* attributes which reduces duplicated code.
Javascript
//Timer //
var seconds = 0,
Score = 0,
index = 0,
timerStarted = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if (seconds > 60 && Score < 30) {
alert("Not enough Score");
}
if (seconds > 0) {
setTimeout(tick, 1000);
}
}
$("#one, #two, #three").click(function () {
if(!timerStarted) {
countdown(60);
timerStarted = true;
}
var dataIndex = $(this).data('index');
if (index == dataIndex) {
Score++;
if(dataIndex == 2) {
index = 0;
} else {
index++;
}
}
$("#score").html("Score: " + Score);
});
HTML
<div id="timer"></div>
<div id="score">Score: 0</div>
<button id="one" type="button" data-index="0">Button1</button>
<button id="two" type="button" data-index="2">Button2</button>
<button id="three" type="button" data-index="1">Button3</button>
Check Fiddle
var seconds=0;
var Score=0;
var index=0;
var started = false;
function countdown(sec) {
seconds = sec;
tick();
}
function tick() {
var counter = document.getElementById("timer");
seconds--;
counter.innerHTML = "Time : " + String(seconds);
if(seconds>60 && Score<30)
{
alert("Not enough Score");
}
if( seconds > 0 ) {
setTimeout(tick, 1000);
}
}
$("button").click(function(){
if(!started){
started = true;
countdown(60);
}
});
You could generate custom event after click
$(window).trigger('clicked');
$(window).on('clicked', function() {
setTimeout(tick, 1000);
});
http://jsfiddle.net/Bwdfw/100/
Just remember to check if the countdown has not started yet.
$("button").click(function(){
});
This will add a handler to all the buttons in your DOM, then just check the status of the countdown.
Check this fiddle:
http://jsfiddle.net/eddiarnoldo/Bwdfw/102/

How can i clearInterval(myFunc) after myFunc has executed 5 times?

The purpose of the code below is to alert online shoppers that they must select a color (via a select/option menu) before putting an item into their basket. If they don't select a color (ie, make a selection) some blinking text displays alerting them.
I'm trying to have the text blink 3 times then stop. I tried using some counter vars but didn't work. How can I re-write this so the blink executes 3 times only?
function blink() {
if ($('.pleaseSelect').css('visibility') == 'hidden') {
$('.pleaseSelect').css('visibility', 'visible');
} else {
$('.pleaseSelect').css('visibility', 'hidden')
}
}
function showNotice() {
timerId = setInterval(blink, 200);
}
$('#addToCart').click(function() {
if ($("select > option:first").is(":selected")) {
showNotice();
} else {
clearInterval(showNotice);
$('.pleaseSelect').css('visibility', 'hidden');
}
})
Well you can have counter declared and incremented each time blink is called. then check if you have called blink three times, clear the interval. Also your showNotice function is not defined properly.
var counter = 0,
timerId;
function blink() {
if ($('.pleaseSelect').css('visibility') == 'hidden') {
$('.pleaseSelect').css('visibility', 'visible');
} else {
$('.pleaseSelect').css('visibility', 'hidden')
if (counter > 4) {
showNotice(false);
}
}
counter++;
}
function showNotice(show) {
if (show) {
timerId = setInterval(blink, 200);
} else {
clearInterval(timerId);
counter = 0;
}
}
$('#addToCart').click(function () {
if ($("select > option:first").is(":selected")) {
showNotice(true);
} else {
showNotice(false);
$('.pleaseSelect').css('visibility', 'hidden');
}
})
Here is working fiddle
function blink(){
var blinkCount = 0;
return function () {
if($('.pleaseSelect').css('visibility')== 'hidden'){
$('.pleaseSelect').css('visibility', 'visible');
} else {
$('.pleaseSelect').css('visibility', 'hidden')
}
blinkCount = blinkCount + 1;
if (blinkCount === 3) {
clearInterval(timerId);
}
}
}
the only thing is that timeId is global - bad practice... however you would have to refactor more of your code in order to correct that issue.
another option is to just fadIn and fadeOut rather than what you're doing.
It would look something like:
if(element.val() == ''){
element.fadeOut("fast");
element.fadeIn("fast");
element.fadeOut("fast");
element.fadeIn("fast");
element.fadeOut("fast");
element.fadeIn("fast");
}
How about this example? Use an anonymous function to call your blink method and keep decrementing a counter.
id = setInterval(function () {
counter--;
if (!counter) {
clearInterval(id);
}
blink();
}, 200);
See the JSFiddle for the complete context.
You can accomplish the desired behavior using variables within a private scope:
$('#addToCart').click(function(e) {
blink(e);
});
function blink(e) {
var blink_count = 0;
var timer = setInterval(function(e) {
blink_count++;
$('.pleaseSelect').toggle();
if (blink_count >= 6) {
clearInterval(timer);
blink_count = 0;
}
}, 200);
}

How do I correctly use setInterval and clearInterval to switch between two different functions?

For practice I am trying to display a number that increments from 0 - 9, then decrements from 9 - 0, and infinitely repeats.The code that I have so far seems to be close, but upon the second iteration the setInterval calls of my 2 respective functions countUp and countDown seem to be conflicting with each other, as the numbers displayed are not counting in the intended order... and then the browser crashes.Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Algorithm Test</title>
</head>
<body onload = "onloadFunctions();">
<script type = "text/javascript">
function onloadFunctions()
{
countUp();
setInterval(countUp, 200);
}
var count = 0;
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count == 10)
{
clearInterval(this);
countDown();
setInterval(countDown, 200);
}
}
function countDown()
{
document.getElementById("here").innerHTML = count;
count--;
if(count == 0)
{
clearInterval(this);
countUp();
setInterval(countUp, 200);
}
}
</script>
From 0 - 9, up and down: <div id = "here"></div>
</body>
</html>
You need to capture the return value from setInterval( ... ) into a variable as that is the reference to the timer:
var interval;
var count = 0;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
/* ... code ... */
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count === 10)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
#Claude, you are right, the other solution I proposed was too different from original code. This is another possible solution, using setInterval and switching functions:
function onloadFunctions() {
var count = 0;
var refId = null;
var target = document.getElementById("aux");
var countUp = function() {
target.innerHTML = count;
count ++;
if(count >= 9) {
window.clearInterval(refId);
refId = window.setInterval(countDown, 500);
}
}
var countDown = function() {
target.innerHTML = count;
count --;
if(count <= 0) {
window.clearInterval(refId);
refId = window.setInterval(countUp, 500);
}
}
refId = window.setInterval(countUp, 500);
}
clearInterval(this);. You can't do that. You need to save the return value from setInterval.
var interval;
function onloadFunctions()
{
countUp();
interval = setInterval(countUp, 200);
}
var count = 0;
function countUp()
{
document.getElementById("here").innerHTML = count;
count++;
if(count == 10)
{
clearInterval(interval);
countDown();
interval = setInterval(countDown, 200);
}
}
function countDown()
{
document.getElementById("here").innerHTML = count;
count--;
if(count == 0)
{
clearInterval(interval);
countUp();
interval = setInterval(countUp, 200);
}
}
try this:
...
<body onload = "onloadFunctions();">
<script>
var cup, cdown; // intervals
var count = 0,
here = document.getElementById("here");
function onloadFunctions() {
cup = setInterval(countUp, 200);
}
function countUp() {
here.innerHTML = count;
count++;
if(count === 10) {
clearInterval(cup);
cdown = setInterval(countDown, 200);
}
}
function countDown() {
here.innerHTML = count;
count--;
if(count === 0) {
clearInterval(cdown);
cup = setInterval(countUp, 200);
}
}
</script>
From 0 - 9, up and down: <div id = "here"></div>
</body>
you could also create a single reference to #here element. Use always === instead of ==
There are many ways to solve this problem, the following is my suggestion:
function onloadFunctions() {
var count = 0;
var delta = 1;
var target = document.getElementById("here");
var step = function() {
if(count <= 0) delta = 1;
if(count >= 9) delta = -1;
count += delta;
target.innerHTML = count;
window.setTimeout(step, 500);
}
step ();
}
PS: it's safer to use setTimeout than setInteval.
/** Tools */
const log = require('ololog').configure({
locate: false
})
let count = 0
let interval__UP
let interval__DOWN
function countUp () {
count++
log.green('countUp(): ', count)
if (count == 5) {
clearInterval(interval__UP)
interval__DOWN = setInterval(function () {
countDown()
}, 1000)
}
}
function countDown () {
count--
log.red('countDown(): ', count)
if (count == 0) {
clearInterval(interval__DOWN)
interval__UP = setInterval(function () {
countUp()
}, 3000)
}
}
function start () {
countUp()
log.cyan('start()')
interval__UP = setInterval(function () {
countUp()
}, 2000)
}
start()
Console Log shows it's working

Categories