setTimeout and setInterval on same function(with parameters) - javascript

I want to set a timeout and an Interval as an onmousedown eventhandler for this function.
function start(clicked_className,clicked_classValue)
{
add(clicked_className,clicked_classValue);
}
startInter=setInterval(start.bind(null,y.className, y.value.replace(/\s/g, '')),600);
That's what I have as working Interval, but don't know how to add timeout without it being 2 separate things. I want the Interval to have a timeout.

You can just put setInterval inside setTimeout function, something like:
el.onmousedown = function() {
start(...)
setTimeout(function(){
// start(...) // maybe also here?
setInterval(function(){
start(...)
},1000)
},5000)
}

setTimeout(function()
{
setInterval(start.bind(null,y.className, y.value.replace(/\s/g, '')),400);
},1000);
worked

Related

clearTimeout on mouseup doesnt work right

I want to click on a point and delete it, but when i press my mouse button down for 3 seconds, i want to do something else with this point. My problem is, that the code doesnt clear the timer, it just deletes the point after 3 seconds, no matter how long i clicked it on the point.
Im working with setTimeout and clearTimeout.
function click(event,d){
timer= setTimeout(function(){
/* do something */
},3000)
}
function clickRelease(timer){
clearTimeout(timer)
}
divMag1=d3.selectAll(".scatterlayer .trace .points path ")
divMag1.on("mousedown", click)
divMag1.on("mouseup",clickRelease)```
V3 - I think you're deleting the target before you can execute what you want.
Note that setTimout may take more than 3 seconds to execute.
Try:
function click(event) {
const currentTarget = event.currentTarget; // for some reason event.target is null in the timer handler, this fixes it 🤷
const timer = setTimeout(() => {
currentTarget.removeEventListener('mouseup', deleteTarget);
console.log('stuff');
// do stuff
}, 3000);
function deleteTarget() {
clearTimeout(timer);
console.log('deleted');
currentTarget.removeEventListener('mouseup', deleteTarget); // not required if you're actually deleting the target
// remove target
}
currentTarget.addEventListener('mouseup', deleteTarget);
}
document.querySelector('#but').addEventListener('mousedown', click)
<button id="but">Click</button>
V1:
let timer;
function click(event,d){
timer= setTimeout(function(){
/* do something */
},3000);
}
function clickRelease(){
clearTimeout(timer)
}
divMag1=d3.selectAll(".scatterlayer .trace .points path ")
divMag1.on("mousedown", click)
divMag1.on("mouseup",clickRelease)
You should first declare timer variable. Then to make your mouseup event works on you should wrap clickRelease to event funtion again or use it simply:
...
.addEventListener("mouseup", function() { clearTimeout(timer) })
Working example with button:
var timer
function click(event, d) {
timer = setTimeout(function () {
console.log('do something')
}, 1000)
}
function clickRelease(timer){
clearTimeout(timer)
}
var divMag1 = document.querySelector('#but')
divMag1.addEventListener("mousedown", click)
document.addEventListener("mouseup", function() { clickRelease(timer) })
<button id="but">Click</button>
If you want event to doing something repeatedly while button is down you need to use setInterval not setTimeout like this:
var timer
function click(event, d) {
timer = setInterval(function () {
console.log('do something')
}, 1000)
}
var divMag1 = document.querySelector('#but')
divMag1.addEventListener("mousedown", click)
document.addEventListener("mouseup", function() { clearInterval(timer) })
Note for clearing interval uses clearInterval not clearTimeout. Also the mouseup event handler attached on whole document in my solution not on button.

How can I break a loop when I'm out of it?

Here is my code:
$(document).on('click', '.fa-search', function () {
while(1) {
magnifire.fadeTo('slow', 0.2).fadeTo('slow', .8);
}
sendAjaxRequest();
// Here I need to break (stop) that while loop
})
As I've commented in my code, I need to stop while(1) after sendAjaxRequest(); executed. How can I do that?
You could use setInterval and clearInterval for this. As their names suggest, setInterval sets a function to execute repeatedly at given interval (1000 ms in example below), and clearInterval stops all further executions.
var interval = setInterval(function() {
console.log("Do something");
// magnifire.fadeTo('slow', 0.2).fadeTo('slow', .8);
},1000);
function Clear() {
clearInterval(interval);
console.log("Stop iterating");
}
<button onclick="Clear()">Click me</button>

delay the on("click") event

I have this code
$("input").on('keyup', function () {
$("block"),slideDown("slow")......
The problem is taht when I write fast the block will do the "animation" again and agin much slower than I write
Is there another event I can use to only run the code "after I'm finished writing" lets say, I stop writing and then it taks 500ms and then the code is executed.
function throttle(fn, time ){
var timer = 0;
return function() {
clearTimeout(timer);
timer = setTimeout($.proxy(fn, this), time);
};
}
$("input").on('keyup', throttle(function () {
$("block").slideDown("slow")
},500));
The throttle returns a new function that calls the old function once 500 milliseconds have elapsed since the function was last called.
Something like this is what I've used before:
$(input).keyup(onKeyUp);
/**
* Handler for the keyup event
*/
function onKeyUp() {
//reset
clearTimeout(myTimer);
myTimer = setTimeout(otherFunction, 500);
}
Now otherFunction will be called after 500 milliseconds, but on each keyup event this timer will be reset.
Try to use...
function slideDown(){
...
}
// call
setTimeout(function(){ slideDown(); }, 1000);

jQuery Fade object after 20 seconds of inactivity

I want to fade out a div if a user hasn't made a mouse click for 20 seconds.
I have the following code:
if($('.main-popup2').is(":visible")){
setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
Problem is I don't know how to reset the setTimeout after detecting a user mouse click.
Thanks!
The .setTimeout() method actually returns a reference to the timer it creates. This reference can be used in .clearTimeout to stop the timer before it executes.
Here is an example of how to use this:
var timer;
if($('.main-popup2').is(":visible")){
// create the timer and save its reference
timer = setTimeout(function() {
$('.main-popup2').fadeOut('fast');
}, 20000);
}
// when clicking somewhere on the page, stop the timer
$(document).click(function() {
clearTimeout(timer);
}):
var timeout = null;
var fadeElement = $('.main-popup2');
function fader() {
if(null !== timeout) {
clearTimeout(timeout);
}
fadeElement.stop();
timeout = setTimeout(function () {fadeElement.fadeOut('fast');}, 2000);
}
$(document).click(fader);
fader();
Use delay function.
(window).click(function () {
$('.main-popup2').delay(6000).fadeOut(300);
}
Each click restart 6 seconds, after it .main-popup2 fadeout if there isn't

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