need to reset the function how do i do it - javascript

I want to reset this flash in between so that i need not have to wait till the end to restart the flash, how do i reset this?
function flash() {
var arrayId = 0,
splitSet = $('#text_original').html().split(" "),
splitSetLength = splitSet.length;
function flashWord() {
$("#flash_word").html(splitSet[arrayId]);
arrayId += 1;
var t = setTimeout(remove, 1000);
}
function remove() {
if (arrayId < splitSetLength) {
$("#flash_word").html(" ");
flashWord();
} //else reset_flash();
}
flashWord(); }
please see the http://jsfiddle.net/HcDfS/

Make the timer variable a global one and cancel the time-out on it (with clearTimeout()). Then, hide #flash_word.
I took the liberty of re-implementing your fiddle:
var timer, words;
function startFlashing() {
words = $("#source").text().split(" ");
showNextWord(0);
}
function stopFlashing() {
clearTimeout(timer);
$("#banner").text("");
}
function showNextWord(index) {
$("#banner").text(words[index]);
index++;
if (index < words.length) timer = setTimeout(function () {
showNextWord(index);
}, 1000);
else $("#banner").text("");
}
​
With HTML:
<p id="source">This is the text to be flashed.</p>
<button onclick='startFlashing()'>Start Flashing!</button>
<button onclick='stopFlashing()'>Stop Flashing!</button>
<p id="banner"></p>​
And it's here: http://jsfiddle.net/CZnVc/6/

Related

how to make it have a wait until it executes a new code

So how do I make it wait 1000 milliseconds until it executes a different code(btw, What is the JavaScript version of sleep()? IS NOT helping me, so PLEASE don't close this question(and I'm not very good with JavaScript)).
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="changeText" style="font-family:verdana;"><br><br>
Press ENTER to continue</div>
<script>
document.addEventListener('keydown',function(e){
if(e.keyCode==13){
newPageTitle = 'Executing...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Loading...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Fetching Data...';
document.title = newPageTitle;
//wait goes here
newPageTitle = 'Done!';
document.title = newPageTitle;
//wait goes here
window.location.href=('https://example.com');
}
});
</script>
<script>
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
</script>
</body>
</html>
what I want it to do is whenever you press enter it changes the title, then it waits 1000 milliseconds to change the tile again, and then it waits 680 milliseconds to redirect you to another webpage (also for some reason when it's in the code snippet you have to click the snippet area and the you can press enter).
To do your animation on the document title, that would be a serie of nested setTimeout() function looking like this:
setTimeout(function () {
document.title = "Executing...";
setTimeout(function () {
document.title = "Loading...";
setTimeout(function () {
document.title = "Fetching Data...";
setTimeout(function () {
document.title = "Done!";
setTimeout(function () {
window.location.href = "https://example.com";
}, 1000);
}, 4000);
}, 3000);
}, 2000);
}, 1000);
I agree that is ugly. And you would have to calculate the added delays from outer to inner... So you could have a function to set the timeouts and make your code readable and maintainable.
Notice that nice looking script:
wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)
Here is a demo where I console logged the title texts... Because we won't see the effect otherwize, since the snippet is an iframe.
document.addEventListener('keydown', function(e) {
if (e.keyCode == 13) {
wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)
}
});
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);
function change() {
elem.innerHTML = text[counter];
counter++;
if (counter >= text.length) {
counter = 0;
}
}
// A global variable to sum up the delays
let wait_time = 0;
function wait(delay, message) {
// Each "wait" call is adding its delay to the global wait_time
wait_time += delay
// This is the delay to use in this timeout
// "let" making it scoped to this function call
let timeoutDelay = wait_time;
console.log(timeoutDelay)
// Set a timeout
setTimeout(function() {
// If there is a message, use it on the title.
// else, redirect
if (message) {
console.log(message)
document.title = message;
} else {
window.location.href = ('https://example.com');
}
}, timeoutDelay)
}
<div id="changeText" style="font-family:verdana;"><br><br> Press ENTER to continue</div>

java script Foreach loop

Javascript
function myFunction() {
for (i = 0; i < 5000;) {
setTimeout(function() {
document.getElementById("demo").innerHTML = i;
}, i);
i += 500;
}
}
HTML
<body onload="myFunction()">
<div id="demo"></div>
How to increase " i " every 5ms and print it in #demo every time it changes
I am trying to make a look that increases the value of ( i ) once every 5ms, and prints it out in # demo.
Right now, the value 5000 immediately prints out as soon as I run the script for some reason, as opposed to increasing by 500 every time.
Thanks in advance.
You can change myFunction to:
var i = 0;
function myFunction() {
var timerId = setInterval(function(){
if(i >= 5000)
{
clearInterval(timerId);
}
document.getElementById("demo").innerHTML = i;
i +=500;
}, 5);
}
this should work.
var i=0;
function looper(){
setTimeout(function(){
console.log(i+" data");
i=i+500;
if(i<5000)
looper();
}, i);
}
looper();
function myFunction() {
var i = 0;
var max = 5000;
var step = 500;
var intervalMs = 5;
var interval = setInterval(function() {
// clear interval if one step before max value
if (i >= max-step) {
clearInterval(interval);
}
// increment i by step
i+=step;
// set inner html of div
document.getElementById("demo").innerHTML = i;
}, intervalMs)
}
Plunkr: https://plnkr.co/edit/IfkGOpjUnf4sKpN4iCZ4?p=preview
If you want your code to look similar to what you have, you can use an IIFE:
function myFunction() {
for (i = 0; i <= 5000;i += 500) {
(function(index) {
setTimeout(function() {
document.getElementById("demo").innerHTML = index;
}, index);
})(i);
}
}
<body onload="myFunction()">
<div id="demo"></div>
</body>
You are having an issue with the closure not saving a reference to your timeout. Subsequent arguments after the second are passed into the callback function as arguments.
Here we are passing i as the third argument
setTimeout(fn, delay, i)
Then in the callaback we have access to the i, we are reassigning it to x within the scope of the callback.
function myFunction() {
for (i = 0; i <= 5000; i = i + 500) {
setTimeout(function(x) {
document.getElementById("demo").innerHTML = x;
}, i, i);
}
}
myFunction()
<div id="demo"></div>
function myFunction(max, ii = 0) {
document.getElementById('demo').innerHTML = ii
if (ii < max) {
setTimeout(myFunction, 500, max, ii + 500)
}
}
myFunction(5000)
<div id="demo"></div>
**
<div id="demo"></div>
<script>
function myFunction() {
var i = 0;
var setClock = function() {
if (i < 5000) {
local = i;
i += 500;
setTimeout(function() {document.getElementById("demo").innerHTML = local; setTimeout(setClock, 500);},
500);
}
}
setClock();
}
**
you should wrap scripts in tags
the javascript Closures. You should know that because of the Closures, second parameters for all setTimeout() are 5000, which is the i's final value. You can avoid the Closure by the codes I showed or erase the impact of Closure by below codes:
<div id="demo"></div>
<script>
function myFunction() {
var local;
for (i = 0; i < 5000; i+= 500) {
local = i;
setTimeout((function(interval){
return function() {document.getElementById("demo").innerHTML = interval;} ;
})(local), (function(interval){return interval})(local));
}
}

Confused about SetInterval and closures

How can we repeatedly update the contents of a div using setInterval
I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?
but i have got few questions here
Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
How can we make it run infinitely, with the following code it gets stopped once i reaches 10.
window.onload = function() {
var timing = document.getElementById("timer");
var i = 0;
var interval = setInterval(function() {
timing.innerHTML = i++;
if (i > 10) {
clearInterval(interval);
i = 0;
return;
}
}, 1000);
}
<div id="timer"></div>
I am confused about setIntervals and closures
can some one help me here
Thanks
You could do something like this with a closure. Just reset your i value so, you will always be within your given range.
window.onload = function() {
var updateContent = (function(idx) {
return function() {
if (idx === 10) {
idx = 0;
}
var timing = document.getElementById("timer");
timing.innerHTML = idx++;
}
})(0);
var interval = setInterval(updateContent, 1000);
}
<div id="timer"></div>
This one should be clearer.
function updateTimer() {
var timer = document.getElementById("timer");
var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
if (timerValue == 10) {
timerValue = 0;
}
timer.setAttribute("data-timer-value", timerValue);
timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>

scope in angular and applied css class only on first div

I'm calling js function every 2 seconds where on certain condition I want to update div on the view.
<div id="ball_{{ballIndex}}">{{ball}}</div>
on ng controller
var myCounter = 0;
var interval = $interval(function () {
if (myCounter <= 35) {
myCounter ++;
DoSomething();
} else {
//
}
}, 1500);
function setCurrentBallEffect() {
$('#ball_' + myCounter).addClass('magictime puffIn');
}
function DoSomething() {
if (myCounter == 0) {
$scope.ballIndex = 1;
} else {
$scope.ballIndex = myCounter;
}
}
using this code only first div in iteration is applied with class magictime puffIn. When I hardcode div id's on the view side like <div id="ball_1">1</div> <div id="ball_2">2</div> .. applied css class work on each div. What I'm doing wrong?
Update:
Tried with
<div ng-attr-id="{{ 'ball_' + ballIndex }}"> </div>
but problem is still present.
At first you must define
var myCounter =0;
I don't understand ball
you must defined it like this :
$scope.ball=0;
I Change view like this
<div id="ball_{{ballIndex}}">{{ballIndex}}</div>
and your javascript changed like this:
var poolCounter = 0;
var myCounter = 0;
var interval = $interval(function () {
if (myCounter <= 35) {
myCounter++;
DoSomething();
} else {
//
}
}, 1500);
function setCurrentBallEffect() {
$('#ball_' + myCounter).addClass('magictime puffIn');
}
function DoSomething() {
if (myCounter == 0) {
$scope.ballIndex = 1;
} else {
$scope.ballIndex = myCounter;
}
}

JQuery Auto Click

I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example

Categories

Resources