How to force restart a javascript function - javascript

Hello i've script which changes me text colors on interval, there is:
<script>
const txts=document.querySelector(".animate-text").children,
txtsLen=txts.length;
let index=0;
const textInTimer=3500,
textOutTimer=3300;
function animateText() {
for(let i=0; i<txtsLen; i++){
txts[i].classList.remove("text-in","text-out");
}
txts[index].classList.add("text-in");
setTimeout(function(){
},textOutTimer)
setTimeout(function(){
},textInTimer);
}
window.onload=animateText;
</script>
<script>
var i = 0;
function changeClass(){
setTimeout(function() {
txts[index].classList.add("text-out");
if(index == txtsLen-1){
index=0;
}
else{
index++;
}
animateText();
$("#animate-button").removeClass("anim" + i)
i = (i==4)?1:i+1;
$("#animate-button").addClass("anim" + (i));
}, 300)
}
setInterval(changeClass, 3500);
windows.onload=changeClass;
</script>
I need to know how can i force to start over this script after switch back to my page.
So next script for restart looks:
<script>
document.addEventListener("visibilitychange", function() {
if (document.hidden){
console.log("Browser tab is hidden")
} else {
console.log("Browser tab is visible")
//Resetowanie slidera
jQuery('#carouselExampleControls').carousel(0);
console.log('Slider został przywrócony do 1 slajdu');
// start over changeClass function here
console.log('Funkcja changeClass zaczęła działać od początku');
}
});
</script>
I need to start over changeClass() function and put it below the comment in last script

Related

jQuery SetTimeout for Show / Hide div does not work

I am writing a jQuery which is supposed show/hide a series of images after an image is clicked. It basically, hides the current image and shows the next one when onClick event.
The function I have written so far works except one feature: On image 3, I want to set a timer and then switch to image 4, even if the user hasn't click it.
I am using a setTimeout and the timeout triggers except that it does not switch to next image.
This is my function:
(function($) {
$(document).ready(function () {
var count = 0;
$('.squirrel').click(function () {
$(this).hide();
var next = $(this).next();
if (next.length == 0){
next = $(this).parent().find('.squirrel').first();
count = -1;
}
next.show();
if (count == 1) {
setTimeout(
function() {
alert("Should switch to 4 now but it doesn't work");
$(this).hide();
var next = $(this).next();
next.show();
count++;
}, 2000
);
} else {
count++;
}
});
});
})(jQuery);
This is the HTML:
<div id="squirrelContainer">
<img src="1.png" class="squirrel default">
<img src="2.png" class="squirrel">
<img src="3.png" class="squirrel" id = "3">
<img src="4.png" class="squirrel">
</div>
Here's a JSFiddle.
Because you are using the same image not the next one.
(function($) {
$(document).ready(function () {
var count = 0;
$('.squirrel').click(function ()
{
$(this).hide();
var next = $(this).next();
if (next.length == 0)
{
next = $(this).parent().find('.squirrel').first();
count = -1;
}
next.show();
if (count == 1)
{
let that = $(this).next();
setTimeout(
function()
{
console.log("Should switch to 4 now but it doesn't work");
that.hide();
var next = that.next();
next.show();
count++;
}, 2000
);
}
else
{
count++;
}
});
});
})(jQuery);
https://jsfiddle.net/dyt9opLz/

How to do this in jQuery?

I want to transform this code from JavaScript into jQuery.
This is the current code:
var i = 0;
var start = true;
document.getElementById("startclick").addEventListener("click", function() {
if (start) {
start = false;
interval = setInterval(function() {
i++;
document.getElementById('list').innerHTML += "albastru_" + i + '<br>' ;
}, 3000);
} else {
start = true;
clearInterval(interval);
}
});
Here is my attempt:
$x = 0;
$start = true;
$(document).ready(function () {
$('#buton2').on('click',function () {
if($start){
$start = false;
$interval = setInterval(function () {
$x ++;
$('#list').html('<p>albastru_</p>' + $x + '<br>'); }, 1000);
} else {
$start = true;
clearInterval($interval);
}
})
});
You can do something like below. I'm assuming startclick is a button, after you click it .append() will add the required data to #list div after 3 seconds.
Updated Answer with start and stop buttons.
var i = 0;
var start = true;
var interval = null;
$('#startclick').click(function() {
if (interval !== null) return;
interval = setInterval(function() {
i++;
$('#list').append("albastru_" + i + '<br>');
}, 3000);
});
$("#stop").click(function() {
clearInterval(interval);
interval = null;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="list">
</div>
<br />
<button id="startclick">START!</button>
<button id="stop">STOP!</button>

jQuery/JavaScript: Initiate and terminate a loop with the same button

I want to build a button that when I click it, the function in JavaScript associated with it initiates (so a loop inside it start doing something).
If I click it again before the loop inside the function finishes, the loop will terminates.
If I click it again after the loop inside the function has already finished, the loop will just start as usual.
How do I do this with the following code?
Thanks in advance.
HTML:
<button id="startstop" class="btn btn-primary" onclick="count()">
JavaScript:
function count() {
var val = 0;
var loop = setInterval(function(){
val++;
if (val > 1000} {
clearInterval(loop);
}
}, 100);
}
try this code
var loop;
function count() {
var val = 0;
if (loop) {
clearInterval(loop);
loop = null;
}
else{
loop = setInterval(function(){
val++;
console.log(val);
if (val > 1000) {
clearInterval(loop);
loop = null;
}
}, 100);
}
}
I'm not a big fan of doing work for people, but on this occasion I'll succumb...
You need to store the internal ID outside of the function, and base your process on that. If the ID is not set, start the interval, if it is set stop the interval.
Note, that I've massively reduced the length of interval, and the number of times it fires for this example...
var _intervalId = -1;
function count() {
if (_intervalId == -1) {
var val = 0;
_intervalId = setInterval(function(){
val++;
if (val > 200) {
clearInterval(_intervalId);
_intervalId = -1
document.getElementById("output").innerHTML = "stopped automatically";
}
}, 10);
document.getElementById("output").innerHTML = "started";
} else {
clearInterval(_intervalId);
_intervalId = -1;
document.getElementById("output").innerHTML = "stopped manually";
}
}
<button onclick="count();return false">Click Here</button>
<div id="output"></div>
Place loop variable in global scope and everytime the user clicked stop previous loop if it's already started if not start it.
Hope this helps.
var loop=null;
count = function () {
var val = 0;
//Stop previous loop if it's already started
if(loop!=null){
clearInterval(loop);
loop=null;
}else{
loop = setInterval(function(){
val++;
console.log(val);
$('span').text(val);
if (val >= 20) {
clearInterval(loop);
}
}, 100);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="startstop" class="btn btn-primary" onclick="count()">Count</button>
<span>0</span>
I had fun building a small class for this. Feel free to use.
// Counter class
function Counter(callback, speed, max, init){
var loop = null;
this.callback = callback;
this.value = init || 0;
this.max = max;
function count(){
if (this.max && this.value >= this.max) {
clearInterval(loop);
loop = null;
} else {
this.value++;
}
this.callback(this.value);
}
this.start = function(){
if(!this.isStarted){
loop = setInterval(count.bind(this), speed);
}
};
this.stop = function(){
if(this.isStarted){
clearInterval(loop);
loop = null;
}
}
Object.defineProperty(this, "isStarted", { get: function(){
return !!loop;
}});
}
// Usage example.
var result = document.getElementById("counter");
var button = document.getElementById("startstop");
// Create the counter and the callback.
var counter = new Counter(function(val){
result.innerHTML = val;
}, 100, 1000);
// Init the result value.
result.innerHTML = counter.value;
// Listen for click events on the button.
button.addEventListener("click", function(){
if(counter.isStarted){
counter.stop();
} else {
counter.start();
}
});
<div id="counter"></div>
<button id="startstop">Toggle</button>

how to clear Interval on Mouse Over in java script?

<script type="text/javascript">
var images=["cod.jpg","cod2.jpg","cod3.jpg","cod4.jpg"];
var i=0;
window.onload=function(){
changeimage();
var stopinterval = setInterval(changeimage,3000);
}
function changeimage(){
if(i==images.length||i>images.length){
i=0;
}
document.getElementById('metroslider').src=images[i];
i++;
}
function stopanim(){
clearInterval(stopinterval);
}
</script>
**body is below **
<div class="sliderbtns" onMouseMove="stopanim();">
But its not working please help me how to stop the interval using On mousOver function .
Thanks .
var images = ["cod.jpg", "cod2.jpg", "cod3.jpg", "cod4.jpg"];
var i = 0;
var stopinterval;
window.onload = function() {
changeimage();
stopinterval = setInterval(changeimage, 333);
}
function changeimage() {
document.querySelector('div').innerHTML = i;
i++;
}
function startAnim() {
if (stopinterval === null) {
stopinterval = setInterval(changeimage, 333);
}
}
function stopanim() {
if (stopinterval) {
clearInterval(stopinterval);
stopinterval = null;
}
}
<div onmouseover="stopanim()" onmouseout="startAnim()">mouse over to stop</div>

Show Div on Mouseover after three second

I want on first click it will show after 3 seconds but after the first click when I clicked it will shown before 3 seconds:
function Func1()
{
document.getElementById('div1').style.visibility = "visible" ;
}
function Func1Delay()
{
setTimeout("Func1()", 3000);
}
function Func2Delay()
{
document.getElementById('div1').style.visibility = "hidden" ;
}
Your English or description is very poor, but from what I understand, you want something like this :
var div = document.getElementById('div1'),t;
function changeStyle(element,prop,value){
element.style[prop] = value;
}
function showDiv(){
changeStyle(div,'opacity','1');
}
function hideDiv(){
changeStyle(div,'opacity','0');
}
div.addEventListener('mouseover',function(){
t = setTimeout(showDiv,3000);
},false);
div.addEventListener('mouseout',function(){
clearTimeout(t);
hideDiv();
},false);​
Here's a demo : http://jsfiddle.net/gion_13/TSVA5/
You have to hover the "invisible" div and it will show after 3 seconds.
this works for me
the markup:
<input type="button" value="clickme" onmouseout="ClearIntv()" onmouseover="DelayShow('showMe',5000)" />
<div id="showMe" style="display:none;background-color:red;width:50px;height:50px;">
</div>
the script:
var intv;
function DelayShow(timeOutMs) {
var elm = document.getElementById("showMe");
var now = new Date().getTime();
var end = now + timeOutMs;;
intv = setInterval(function () {
now = new Date().getTime();
if (now >= end) {
elm.style.display = "block";
clearInterval(intv);
}
}, 500);
}
function ClearIntv() {
clearInterval(intv);
}
Activates the counter on MouseOver, and cancels on MouseOut

Categories