Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
clearInterval(interval)
var interval = setInterval(function(){
console.log('running')
},1000);
I have above code in a click event, the console.log('running') turn out to be trigger multiple times when I execute above code, why? I already clear the interval first before run the setInterval.
Assuming your code looks something like this:
$('#someButton').on('click', function() {
clearInterval(interval)
var interval = setInterval(function(){
console.log('running')
},1000);
});
then the problem you're having is all to do with scope. The second time your button is clicked, the function will run, but will have no reference to any variables created inside the function the first time it ran. (Try adding console.log(interval) as the first line in the click handler function). To solve this, you'll need to keep a reference to interval somewhere that the click handler can access it. For example:
var interval = null;
$('#someButton').on('click', function() {
clearInterval(interval)
interval = setInterval(function(){
console.log('running')
},1000);
});
See What is the scope of variables in JavaScript? for some examples of scope in action.
Ok, now I understand your problem. You need to declare interval in a higher scope (global if needed).
Your problem is the interval varible is declare inside the click function and therefor it's a local varible, you need to keep it elsewhere to access the reference in order to clear it.
Try this, and do not put all this in the click function, put it on the same level with the click function should work.
var interval;
function doInterval() {
if (interval != undefined) clearInterval(interval);
interval = setInterval(function(){
console.log('running');
},1000);
}
P/S: you should edit your question to clarify the question.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 months ago.
Improve this question
Does anyone have any idea how to stop an interval that is situated inside of a function once it's done doing its thing?
Here is what I mean:
function renderMessage(message) {
const renderInterval = setInterval(() => {
characterIndex++;
dealerMessage.innerHTML = `
${messages[message].slice(0, characterIndex)}
`;
if (characterIndex === messages[message].length) {
clearInterval(renderInterval)
}
}, 100);
}
As you can see, I'm trying to render out a message using this function. It does its job fine, but if I don't stop it, subsequent messages keep overriding themselves...
I've tested the if check and it is actually functioning inside the function, yet for some reason the clearInterval doesn't work.
Is there any way I can fix this, or do you recommend me to start from scratch?
Note: this method would be very handy for me, so, if possible, I would like to keep it.
I think your 'if' statement of clearInterval should be
if (characterIndex===message[message.length]){}
Also, I cannot see any initialization of the characterIndex variable. Please do inform if this worked or not.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm trying to use setTimeout, But it doesn't work. Any help is appreciated.
Anyone know how to fix this?
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = 1000;
setTimeout(startTimer(), startInterval);
}
function startTimer() {
document.write("hey");
}
This line:
setTimeout(startTimer(), startInterval);
You're invoking startTimer(). Instead, you need to pass it in as a function to be invoked, like so:
setTimeout(startTimer, startInterval);
If your in a situation where you need to pass parameters to the function you want to execute after timeout, you can wrap the "named" function in an anonymous function.
i.e. works
setTimeout(function(){ startTimer(p1, p2); }, 1000);
i.e. won't work because it will call the function right away
setTimeout( startTimer(p1, p2), 1000);
Two things.
Remove the parenthesis in setTimeout(startTimer(),startInterval);. Keeping the parentheses invokes the function immediately.
Your startTimer function will overwrite the page content with your use of document.write (without the above fix), and wipes out the script and HTML in the process.
If you want to pass a parameter to the delayed function:
setTimeout(setTimer, 3000, param1, param2);
Use:
setTimeout(startTimer,startInterval);
You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().
Please change your code as follows:
<script>
var button = document.getElementById("reactionTester");
var start = document.getElementById("start");
function init() {
var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
setTimeout(startTimer,startInterval);
}
function startTimer(){
document.write("hey");
}
</script>
See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.
To make little more easy to understand use like below, which i prefer the most. Also it permits to call multiple function at once. Obviously
setTimeout(function(){
startTimer();
function2();
function3();
}, startInterval);
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I would like you to tell me if there is an event that returns to me when it was the last time a user touched the screen, since I need a function to run 3 seconds after the user touched the screen for the last time
There's no specific event for your use-case. What you can do however is adding a click event listener to your window object and assign the current time to a global variable as soon as someone clicked the screen. Additionally you have to use JavaScript's setInterval() method, which executes a function periodically e.g. every 20 ms. Inside it's callback function you can compare the current time to the time stored in the global variable and if the difference is bigger than 3000 trigger your action.
Here's an example (just click 'Run code snippet'):
var timeClicked;
function screenClicked() {
timeClicked = new Date();
}
function check() {
if (timeClicked != null) {
if (new Date() - timeClicked > 3000) {
clearInterval(interval);
alert("time's up!");
}
}
}
window.addEventListener("click", screenClicked);
var interval = setInterval(check, 20);
<body bgcolor="#eeeeee"><span>click anywhere inside this window</span></body>
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I'm sure this is a very simple solution. I have made this javacript function that tests whether there is a certain css style on a div and then moves around another div. However, it does not work and I have no idea why.
JavaScript:
function sale() {
var style = document.getElementsByClassName("product-single__price--wrapper").getAttribute("style");
if (style !="display: none;") {
document.getElementByClassName("product-single__description").style.marginTop = "70px !important";
}
}
window.onload = sale;
I wouldn't ever suggest doing this, but if you want to call that function all the time, you need to put it into a setInterval with the milliseconds you want it to get called.
Example:
$(document).ready(function() {
setInterval(function() {
sale();
}, 1000);
});
OR
$(document).ready(function() {
setInterval(sale, 1000);
});
This will get called every second. Again, horrible horrible horrible practice. But, this will do what you want. If you want it called sooner, then change the milliseconds accordingly (1000 milliseconds = 1 second).
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
I have written this javascript code to add images each after a delay of 3 seconds but this code is not working kindly help.
function start() {
while(true) {
setTimeout(addObstracles(), 3000)
}
}
function addObstracle() {
var element = document.createElement('img');
element.id = 'obs';
element.className = 'obstracleAnimation';
element.src = 'enemy.png';
element.style.position = 'absolute';
element.style.top = '0px';
element.style.left = '100%';
element.style.width = '150px';
element.style.height = '100px';
document.body.appendChild(element);
}
setTimeout takes a function reference. You have a function invokation.
There are multiple ways to write this out:
setTimeout('addObstracles()', 3000) //i don't like this way
setTimeout(addObstracles, 3000) // pass the reference (I like this way!)
setTimeout(function() {
addObstracles()
}, 3000) //I like this when `addObstracles has parameters!
Like Sterling mentioned in his anser, you are calling the function addObstracles instead of passing it to setTimeout, just i want to add to it that because you are setting timout functions on fixed intervals you can use setInterval function instead:
function start() {
setInterval (addObstracles, 3000);
}
JSFiddle
There are multiple issues with this code. I will add to the answers the following:
be careful what function you define and what function you call: something != somethings
be careful where you call your start() function: it has to be after the body tag or body.appendChild won't exist
be careful how you style your element. With the current styling, it is not displayed at all. I have just removed element.style.position = 'absolute'; to make it visible
make sure the image you are trying to display is in the same folder as the script