Using keyframes to translate calendar days on switching between months [duplicate] - javascript

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);

Related

Can someone tell me why this javascript function does not execute? [closed]

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).

reset interval doesn't work in javascript [closed]

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.

Uncaught TypeError: Cannot set property 'innerHTML' of null countdown timer [closed]

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 6 years ago.
Improve this question
I am a JavaScript newbie, I am trying to build a simple countdown timer that counts down only in seconds. It is showing uncaught type error for x. Which what I think means that the function is not recursing. The code is as below:
function timer(x, elem){
var elem = document.getElementById(elem);
elem.innerHTML = x;
if (x > 0) {
setTimeout(timer(x-1, elem),1000);
}
}
You have two issues:
You are overwriting the value of elem to be a DOM element, and then trying to reuse it as if it were still a string
setTimeout expects a function that it can call every 1000 ms. Instead you are calling a function and passing the result to setTimeout. The distinction is a little confusing, but it may help to see it separated out into another variable:
This is what you are currently doing
var myFuncResult = timer(x-1, elem); // this returns the result of the function
setTimeOut(myFuncResult, 1000);
Instead you want
var myFunc = function() { timer(x-1, elem) }; // this returns a function that can be called
setTimeOut(myFunc, 1000);
Of course you can put the function directly into setTimeout, like you attempted to do.
The following does what you want (Hit "Run"):
function timer(x, elem){
var DOMelem = document.getElementById(elem);
DOMelem.innerHTML = x;
if (x > 0) {
setTimeout(function() {
timer(x-1, elem)
},1000);
}
}
timer(10, "my-timer");
<div id="my-timer"></div>

Javascript best practices - where's the best place to define a helper function inside a loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
What's a better practice, this:
myArray.forEach(function(item)) {
doSomething(item);
function doSomething(an_item) {
console.log(an_item);
}
}
or this:
myArray.forEach(function(item)) {
doSomething(item);
}
function doSomething(an_item) {
console.log(an_item);
}
Does the first example create multiple instances of the function, or does it create it just the first time through the loop?
Thanks for any insight!
myArray.forEach(function(item)) {
doSomething(item);
}
function doSomething(an_item) {
console.log(an_item);
}
this function is best because it will created only one time ;
and
myArray.forEach(function(item)) {
doSomething(item);
function doSomething(an_item) {
console.log(an_item);
}
}
is a bad due to every time function will create during loop process
The second. Use the second form (because the first form will slow down your user's experience, which may well be a phone or low powered device), or the even shorter form
myArray.forEach(doSomething);
function doSomething(element, index, array) {
console.log("myArray[" + index + "] = " + element);
}
It really depends on the interpreter if your asking a pure question about performance, i would imagine some of the smarter ones would be good enough to not create and destroy the function each time if they never change during the loop but realistically thats what your telling it to do (Create the function each time as the scope is temporary) so don't be surprised if thats the case. imagine if for example you were dynamically creating a closure within the forEach, wouldn't each loop need to create a new copy of the function?
http://jsperf.com/closure-vs-name-function-in-a-loop/2
certianly I would imagine older browsers not being smart enough to know to only make it once.
another post: Don't make functions within a loop
I agree with what the others have said, and +1 on the second solution. You don't ever want to define/create functions within loops.
**Bonus
If you're function has to do with an object within the forloop, you can use this in your helper instead of passing the object via a parameter:
Example:
var myArray = [{ a: 1 }, { a: 2 }, { a: 3 }];
myArray.forEach(function(item) {
doSomething.call(item);
});
function doSomething(item) {
console.log(this.a);
}
It is good practice to always define things in the smallest scope possible.
So when you don't need the function elsewhere, defining it in the loop which uses it is the best choice.

How to add sleep or wait for JS using JS or jQuery? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
How to add sleep from this function ShowSC()
function ShowSC(){
$("#SC").html('LOADING');
//adding the sleep 1 second
$("#SC").html('<img src="secure/captcha/securimage_show.php" class="img_middle" />');
}
ADVANCE THANKS!
Sorry, I can't find a solution from other question so I just start a question here.
You can use setTimeout, it executes a function, once, after waiting a specified number of milliseconds
function ShowSC(){
$("#SC").html('LOADING');
//adding the sleep 1 second
setTimeout(function(){
$("#SC").html('<img src="secure/captcha/securimage_show.php" class="img_middle" />');
}, 1000);
}
Here 1000 is in milliseconds
The jQuery Way™ is to use delay and queue:
$('#SC')
.html('LOADING')
.delay(1000)
.queue(function (n) {
$(this).html('<img src="secure/captcha/securimage_show.php" class="img_middle" />');
n();
});
It helps maintain chainable code, which can tend to be more readable. Readable code is easier to maintain and extend.
The vanilla JavaScript way is to use a callback in setTimeout:
$('#SC').html('LOADING');
setTimeout(function () {
$('#SC').html('<img src="secure/captcha/securimage_show.php" class="img_middle" />');
}, 1000);
Chaining setTimeout calls within setTimeout calls can end up with callback arrow code, so I generally recommend making use of queueing even if you're not using jQuery. You'd want to make use of some sort of queueing.
The following example makes use of a Queue class that I wrote:
(function () {
var sc,
q;
q = new Queue();
sc = document.getElementById('SC');
sc.innerHTML = 'LOADING';
q.queue(function (n) {
setTimeout(n, 1000);
},function (n) {
sc.innerHTML = '<img src="secure/captcha/securimage_show.php" class="img_middle" />';
n();
});
}());

Categories

Resources