I don't understand clearInterval() - javascript

I have play and skip buttons for JSON array working fine:
jQuery:
$(function() {
// Fetch the initial image
fetchImage(index);
// Event listeners
$("#play").click(function() { fetchImage(next); setInterval(function() { fetchImage(next); }, 1000); return false;});
$("#stop").click(function() { clearInterval(xxx); return false;});
$("#prev").click(function() { fetchImage(prev); return false;});
$("#next").click(function() { fetchImage(next); return false;});
});
xxx should preferably be a variable I read. setInterval() returns a value. I've read several examples. I have not been successful.
Test page: http://flamencopeko.net/icons_cogo_16.php
JSON thing: http://flamencopeko.net/icons_ajax.php
Source: http://flamencopeko.net/icons_cogo_16.txt
Source: http://flamencopeko.net/icons_ajax.txt

You have to name your interval first to be able to clear it. Here's what I would do to your code:
var newInterval;
// Event listeners
$("#play").click(function() {
fetchImage(next);
newInterval = setInterval(function() {
fetchImage(next);
}, 1000);
return false;
});
$("#stop").click(function() {
clearInterval(newInterval);
return false;
});

You need to assign the setInterval function to a variable
var interval = setInterval(function () {});
clearInterval(interval)
I am assuming that is what you are after.

you gave the answer yourself
"it returns a value"
so let it return an alias for a value, a so called variable, ideally you declare it before so it doesnt throw undefined exception when you try to clear it an no #play was clicked befre
var xxx;
...
$("#play").click(function() { fetchImage(next);xxx=setInterval(function() { fetchImage(next); }, 1000); return false;});
...
clearInterval(xxx)...

Have you ever used one of those "take a number" devices which extrude numbered slips of paper?
The return value from setInterval() is like a "Repeating Task ID#".
You shouldn't care how big the number is, but you should store it somewhere, and then you can pass it back into clearInterval() to tell the system which task to stop running.

Related

Ignore function if occurred within x seconds

Since people are misunderstanding my wording, I will rewrite it, I want "with the following code below" to ignore the function which i have commented on below in my jquery if it happened in the last "X" seconds.
Here is my code.
EDIT:: Please write answers in reference to this, example. "the script ignores the change in class and the delay wont work" http://www.w3schools.com/code/tryit.asp?filename=FBC4LK96GO6H
Sorry for confusing everyone including myself.
Edited due to author's post update.
You can create custon event. By this function you will define: "delayedClick" event on the selected objects.
function delayedClickable(selector, delayTime){
$(document).ready(function(){
$(selector).each(function () {
var lastTimeFired = 0;
$(this).click(function(){
if(Date.now() - delayTime > lastTimeFired) {
lastTimeFired = Date.now();
$(this).trigger('delayedClick');
}
});
});
});
}
Remeber that you should define delayTime and this event on selected elements by:
var delayTime = 3 * 1000; // 3 sec delay between firing action
delayedClickable('.Img2', delayTime);
And then just use your event on elements. For example click event can be used in that way:
$element.on('click', function () {
// ...
});
And your custom delayedClick event should be used in that way:
$element.on('delayedEvent', function () {
// ...
});
Full example:
http://www.w3schools.com/code/tryit.asp?filename=FBC56VJ9JCA5
#UPDATE
I've found some another tricky way to keep using click function and makes it works as expected:
function delayedClickable(selector, delayTime){
$(document).ready(function(){
$(selector).each(function () {
var scope = this;
$(this).click(function(){
scope.style.pointerEvents = 'none';
setTimeout(function () {
scope.style.pointerEvents = 'auto';
}, delayTime);
});
});
});
}
And then
var delayTime = 3 * 1000; // 3 sec delay between firing action
delayedClickable('.Img2', delayTime);
That's all.
The key of second way is that we are disabling any pointer event on element when clicked and then after timeout we're turning these events back to work.
https://developer.mozilla.org/en/docs/Web/CSS/pointer-events
And full example:
http://www.w3schools.com/code/tryit.asp?filename=FBC678H21H5F
Can use setTimeout() to change a flag variable and a conditional to check flag in the event handler
var allowClick = true,
delaySeconds = 5;
$(".element1").click(function(){
if(!allowClick){
return; // do nothing and don't proceed
}
allowClick = false;
setTimeout(function(){
allowClick = true;
}, delaySeconds * 1000 );
// other element operations
})

Don't really know how to create time loop for this JS function

i don't really know how to create time loop for this JS function..
Here is that function: enter link description here
Just what i need is a time loop every 20 seconds for a random sort..
I used - var ... = setInterval(..., 20000);
And - var ... = setTimeOut(...,20000);
But i don't know where to connect or if someone know better way how to do that everything gonna help me with that..
Thanks a lot for any help..
You have several issues with your attempt, the below will do what you want, just adjust the timer as needed
Updated CodePen
function loop() { // you had $(function loop(){... here, that is not right
$container = $('#Container');
if ($container.mixItUp('isLoaded')) { // check if the plugin has been initialized
$container.mixItUp('sort', 'random', true); // if loaded, just resort
// change true to false, to forego the animation
} else {
// if not initialized, do that now
$container.mixItUp({
load: {
sort: 'random'
},
layout: {
containerClass: 'list',
display: 'block'
}
});
}
}
$(function() { // here you had a for loop, not sure why but the int should have been var, anyway, I removed it altogether
setInterval(loop, 2000);
});
Try this:
http://codepen.io/anon/pen/BoZvEx
$(document).ready(function () {
var mixit = $('#Container').mixItUp({
load: {
sort: 'random'
},
layout: {
containerClass: 'list',
display: 'block'
}
});
function loop() {
mixit.mixItUp('sort', 'random');
};
var looper = setInterval(loop, 1000);
});
In there, the code is inside a $(document).ready, and there first we instantiate once, with the config in the parameter, and then the method loop does exactly just one call to sort.
$(document).ready(function(){
setTimeout(function(){
for( var i = 0; i < 10; ++i )
{
loop();
}
},20000);
});
I think you need this

Java script : How to find setInterval function is now running or timedout?

In my project I use two setInterval functions, One function is running all time. The second function is start and stop dynamically according to keyboard input. How to find state(Running or Timeout) of second setInterval funcion?
setInterval(function()
{
if(//want to check state of seInterval Function fire)
{
//somecode
}
},300);
var fire=setInterval(function()
{
// some code
},300);
Better add a boolean variable isRunning to the methods in setInterval. Toggle the value according to it. Using the value you can track the status.
Based on the code you have posted:
isFirstInstanceRunning =true;
isSecondInstanceRunning = false;
setInterval(function() {
//want to check state of seInterval Function fire
if(isFirstInstanceRunning){
//somecode
}
},300);
//--- Pass a boolean parameter as "true" onKeypress
function startSecondInstance(toCheck) {
var fire=setInterval(function() {
//want to check state of seInterval Function fire
if(toCheck){
//somecode
}
},300);
}
//---Similarly when you stop the second method
function stopSecondInstance() {
clearInterval(fire);
isSecondInstanceRunning = false;
}
No, not directly, however you could set a variable to check on periodically to see if it's running:
var isRunning = false;
//Start it
var timer = setInterval(function() {
//yada yada function stuff
isRunning = true;
}, 3000);
//Check it
if (isRunning) console.log("Running!");
//Stop it
clearInterval(timer);
isRunning = false;

On keypress, when stop after X seconds call function

I have a text input and a textarea and I'm passing the value from the input to the textarea. I am trying to do, when you type something in the input and you stop, after 2 seconds show the values to the textarea.
In this example the textarea gets the input's value instantly:
http://jsfiddle.net/DXMG6/
So i want, when you type and stop, after 2 seconds give the value.
How can I achieve this? I tried to use setTimeout but when the 2 seconds pass, then it keeps getting the value instantly. So basically it works for the first 2 seconds.
You have to reset the timer everytime the user presses the key again:
jQuery(function($){
function changeFn(){
alert('Changed');
}
var timer;
$("#string").bind("keyup", function(){
clearTimeout(timer);
timer = setTimeout(changeFn, 2000)
});
});
Once i made this plugin called bindDelay for jQuery:
$.fn.bindDelay = function( eventType, eventData, handler, timer ) {
if ( $.isFunction(eventData) ) {
timer = handler;
handler = eventData;
}
timer = (typeof timer === "number") ? timer : 300;
var timeouts;
$(this).bind(eventType, function(event) {
var that = this;
clearTimeout(timeouts);
timeouts = setTimeout(function() {
handler.call(that, event);
}, timer);
});
};
Used like a normal bind method but the last argument is the delay before firing the handler (in mil sec):
$("input").bindDelay('keyup', function() {
$("textarea").text( $(this).val() );
}, 2000);
See fiddle: http://jsfiddle.net/c82Ye/2/
And you unbind and trigger it like normal:
$("input").unbind("keyup");
$("input").trigger("keyup");
setTimeout returns an ID of the "job". what you have to do is to clearTimeout(id) every type and setTimeout again:
var tID = null;
onclick() {
if (tID !== null) clearTimeout(tID);
tID = setTimeout(function() { /*Do domething*/ }, 2000);
}
What you need to do is set a timeout, and save the resulting timeout id. Then you need to check if the timeout id has been saved at each keypress. If the timeout is set, clear the timeout and reset it. Something like this:
var timeoutId = null;
var myFunc = function() {
timeoutId = null;
// Do stuff
};
var myEventHandler = function() {
if (timeoutId) {
window.clearTimeout(timeoutId);
}
timeoutId = window.setTimeout(myFunc, 2000);
};
...or check the updated fiddle:
http://jsfiddle.net/DXMG6/5/
I've updated your fiddle
This will update the textarea value 2 seconds after you end editing the text.
The relevant part is this: we keep a reference to a timeout, when the keyup event is fired we clear the previous timeout and we start a new timeout, that will fire in 2 seconds.
var timeout = null;
$("#string").on("keyup keypress paste mouseup", function () {
clearTimeout(timeout);
timeout = setTimeout(function() {
// ... your code here
}, 2000);
});
Try something like this. Use setTimeout, but each time a key is pressed, reset the timer and start over...
http://jsfiddle.net/DXMG6/10/
var textTimer=null;
$("#string").on("keyup keypress paste mouseup", function () {
if (textTimer) clearTimeout(textTimer);
textTimer = setTimeout(function(){
var a = $('#string').val();
$('#rdonly').html(a);
}, 2000);
});
$('.btn').click(function() {
$('#rdonly').text('');
$('#string').val('');
});
You just need to modify your code as follows:
var timeoutId = 0;
$("#string").on("keyup keypress paste mouseup", function () {
var a = $('#string').val();
// Cancel existing timeout, if applicable
if (timeoutId > 0) {
window.clearTimeout(timeoutId);
}
// Start a timeout for 2 seconds- this will be cancelled above
// if user continues typing
timeoutId = window.setTimeout(function () {
$('#rdonly').html(a);
}, 2000);
});

jquery/javascript blur/focus & settimeout

When mouse is over a product number (focus) then show some product information.
When user is not longer over a product number (blur), then wait 3 seconds, then hide details.
$('.productNumber').live('blur', function() {
setTimeout(function(){
var divToPutData = $(this);
divToPutData.hide();
}, 3000);
});
Now user says that if user moves mouse back within those 5 seconds to stop the count down, until a blur event fires again. No sure how to do this with setTimeout.
Use clearTimeout()
var myTimeout = null;
$('.productNumber').live('mouseover', function() {
//If timeout is still active, clear
if(myTimeout != null)
clearTimeout(myTimeout);
});
$('.productNumber').live('blur', function() {
//Store the ID returned by setTimeout
myTimout = setTimeout(function(){ divToPutData.hide(); }, 3000);
});
Use the function clearTimeout.
setTimeout returns a numeric id, you can store it in a variable, and then pass it to the clearTimeout function:
var myTimeout = setTimeout ( function(){alert(2);}, 1000);
clearTimeout(myTimeout);
var t;
$('.productNumber').live('mouseover', function() {
clearTimeout(t);
});
$('.productNumber').live('mouseout', function() {
t = setTimeout(function(){
divToPutData.hide();
}, 3000);
});
have the setTimeout assigned to a variable, so you can cancel it on hover again
var hideTimeout;
$('.productNumber').live('blur',function() {
hideTimeout = setTimeout(function() {
divToPutData.hide();
}, 3000);
});
$('.productNumber').live('mouseover',function() {
clearTimeout(hideTimeout);
// Do the show stuff
}
jQuery is not my strongest language, so you may need to modify this slightly, but this is the general approach to this scenario.
Use the jQuery stop() to abort any ongoing animation
Test it here: http://jsfiddle.net/T7kRr/1/
jQuery
$(".productNumber").hover(
function () {
$(this).find(".productDesc:last").stop(true, true).show();
},
function () {
$(this).find(".productDesc:last").delay(3000).fadeOut();
}
);
HTML
<div class="productNumber">1001<span class="productDesc" style="display:none">iPhone</span></div>
<div class="productNumber">2001<span class="productDesc" style="display:none">iPad</span></div>
<div class="productNumber">3333<span class="productDesc" style="display:none">TV</span></div>
<div class="productNumber">9999<span class="productDesc" style="display:none">HiFi</span></div>

Categories

Resources