On button next click (Game context), I want to make pause to show correct answer before showing next question. how can I do it?
I try this :
showCorrectAnswer();
questionCounter++;
setTimeout(displayNext(), 6000);
/* Or */
showCorrectAnswer();
questionCounter++;
wait(6000);
displayNext();
/*with wait*/
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
But does not work.
Thanks
You are supposed to pass either an anonymous function to setTimeout() (in which you place what you want to execute when the timeout expires) or the name of a defined function. If you place () after the name, as you did, the function is executed when the setTimeout() is parsed, not when it expires, expecting the result of running your function to return another function that will be executed when the setTimeout() expires - much like the anonymous function does.
Either of the following will work as expected. Name of function:
showCorrectAnswer();
questionCounter++;
setTimeout(displayNext, 6000);
...or anonymous wrapper:
showCorrectAnswer();
questionCounter++;
setTimeout(function(){
displayNext();
}, 6000);
In most real life scenarios, it is advisable to change questionCounter value inside the displaynNext() function, not before.
With jquery you can use:
$('.container').hide().delay(6000).fadeIn(displayNext());
check out this
you have done a small mistake setTimeout(displayNext(),6000) which calls immediately instead you should only pass function name. setTimeout(displayNext,6000)
If you want to do call with parameters make sure you write as a function and then put all your code inside it setTimeout(function(){displayNext(parameter1,parameter2);},6000)
function displayNext(){
alert("display");
}
<input type="number" step="1000" id="num_milisecond" value=1000> milliseconds
<input type="button" onclick="setTimeout(displayNext, document.getElementById('num_milisecond').value);" value="click to allert">
Related
<input autocomplete="off" [config]="config2" [items]="items2" (inputChangedEvent)="onInputChangedEvent($event)" (selectEvent)="onSelect($event)">`enter code here`
onInputChangedEvent(val: string) {
this.changeEvent.emit(val);
this.inputChanged = val;
if (this.timer) {
clearTimeout(this.timer);
}
// trigger the search action after 400 millis
this.timer = setTimeout(this.searchFunction(val), 200);
}
I am using InputChangedEvent ,how can we delay the event
You can't pass a function with arguments to setTimeout(), you need to create another function where in you call this function:
var _this = this;
setTimeout(function () {
_this.searchFunction(val);
}, 200);
By passing the function directly to setTimeout, JavaScript executes the function and uses the return value as the callback. So your searchFunction is executed every time.
Are you asking how to trigger the action only if there has been no typing for 400msec?
If so, the usual approach is a "deadman's switch" (name borrowed from an old safety device on trains, I believe).
The basic idea is that each time you see a keystroke, you kill the existing timer (if any) and start a timer for 400msec.
Then, if the timer finally triggers, you know that 400msec have passed without a keystroke, and you can do the action.
Reference code:
function sleep( sleepDuration ){
var now = new Date().getTime();
while(new Date().getTime() < now + sleepDuration){ /* do nothing */ }
}
function submit_answer(label) {
let image = get_node('img.to_label')
let size = Math.floor(Math.random() * 500)
image.src = `http://via.placeholder.com/${size}x${size}`
setTimeout(sleep.call(this, 1000), 0)
}
submit_answer is called from a click handler.
Desired function: the image is rendered, and the user is forced to wait 1 second before interacting with the page in any way.
Actual function: the user waits 1 second, and the image loads.
I thought setTimeout would put sleep on a queue - I was hoping that the image would be rendered before they were made to wait. How can I force the image to render, and then force the user to wait?
setTimeout() and setInterval() take a function reference or code as a string (but, don't do that) as their first argument. Your code:
setTimeout(sleep.call(this, 1000), 0)
passes an actual function invocation of sleep and that's why you get sleep first (it's being called immediately) and the image load second. The return value from the function invocation is what winds up getting used as the function reference, but sleep doesn't return a value, so undefined winds up being passed to the timer and so nothing happens when the timer expires. The line would need to be:
setTimeout(function(){ sleep.call(this, 1000) }, 0)
so that a function reference would correctly be the first argument and the call to sleep wouldn't happen immediately.
From the docs:
Syntax:
var timeoutID = scope.setTimeout(function[, delay, param1, param2, ...]);
var timeoutID = scope.setTimeout(function[, delay]);
var timeoutID = scope.setTimeout(code[, delay]);
NOTE: code
An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.
Also, setting a timer delay of 0 will never happen. The JavaScript runtime is synchronous and will only run the callback function specified in the timer when it has nothing else to do. As a result, you can never really know for absolute certain what the delay will wind up being. Think of the delay as the minimum amount of time you can expect to wait for your function to run. Having said that, I read somewhere that there was an absolute minimum of 16ms due to the latency between the JavaScript runtime and the browser's WebAPI.
Now, you are going to need to be able to trap the moment that the image actually gets rendered and that can be accomplished with .requestAnimationFrame().
Then, what you need to do is much simpler. You set your timer to start as soon as the image has finished loading and that is done by setting up a callback on the image's load event.
But, your code does nothing to prevent the user from interacting with the page, so you'll need to add a "mask" over the page that prevents interaction.
I've made the timer 3 seconds and given the mask a grey color in the snippet below to show the effect better.
var mask = document.getElementById("mask");
function startRender() {
// Rendering started, run callback when next render occurs
requestAnimationFrame(rendered);
}
function rendered() {
sleep(3000); // Render complete
}
// Nothing happens until the image fires off its load event...
document.querySelector("img").addEventListener("load", function(){
// Run callback when next render occurs
requestAnimationFrame(startRender);
});
function preventKeystrokes(evt){
preventDefault();
}
function sleep(duration){
mask.classList.remove("hidden"); // Show mask to prevent interactions
window.addEventListener("keydown", preventKeystrokes); // prevent keystrokes
// Count to three
setTimeout(function(){
mask.classList.add("hidden"); // Remove mask
window.removeEventListener("keydown", preventKeystrokes); // Enable keyboard
}, duration);
}
#mask { position:fixed; top:0; left:0; z-index:99; background-color:rgba(0,0,0,.6); width:100%; height:100%; }
.hidden { display:none; }
<button>Try to click me!</button>
<img src="http://imgsrc.hubblesite.org/hvi/uploads/image_file/image_attachment/30466/STSCI-H-p1801a-m-2000x1692.png" alt="big image">
<div id="mask" class="hidden"></div>
Let's say I have an input in wich the user is going to type some text. When he finish typing I want to call a function automatically.
This is what I have done till now:
<input type="text" oninput="change();"/>
<script>
function changing(){
alert('You stoped typing!');
}
function change(){
clearTimeout(changing);
setTimeout(changing, 2000);
}
</script>
What I am expecting :
When you type, change is called. It cancels the last changing that was supposed to run in 2 seconds and run a new changing within 2 seconds.
What actually happens :
When you type, change is called. It doesn't cancel the last changing that was supposed to run in 2 seconds but still run a new changing within 2 seconds. As you type, the first alert window will appear 2 seccond after you start typing and keep showing again and again one after another.
Is there something wrong in my code?
setTimeout() returns a timer ID. It is that timer ID that you must pass to clearTimeout() for it to work properly (you are passing the callback function to clearTimeout() and that is not how it works).
So, you need to store the return value from setTimeout() into a variable in a lasting scope that you can then later pass to clearTimeout() like this:
<input type="text" oninput="change();"/>
<script>
function changing(){
alert('You stoped typing!');
}
var timer;
function change(){
clearTimeout(timer);
timer = setTimeout(changing, 2000);
}
</script>
The setTimeout() function returns a value that must be used later with clearTimeout() if you need to cancel it.
var timer;
function changing(){
alert('You stoped typing!');
}
function change(){
clearTimeout(timer);
timer = setTimeout(changing, 2000);
}
I use setInterval and clearInterval in js, when 1st page load
var timer_detail=setInterval(function page1_load(){
......
},5000);
When I go to 2nd page
function page2_load(){
clearInterval(timer_detail);
}
but timer don't stop and I don't know why?
Make the interval variable global replacing:
var timer_detail = ...
with
window.timer_detail = ...
This should fix any scope issues but if it doesn't then add an alert to the page2_load function to ensure the function is being executed when expected.
function page2_load(){
alert('page2_load');
clearInterval(timer_detail);
}
One the second page add
<body onload="page2_load()">
this will executed your function.
please not that I also got ride of the "+" in the function name. because you cant have symbols in a function name.
it should be
function page2_load(){clearInterval(timer_detail)}
I have an html page that links to a js file that has the following function:
function show360Simple( divContainerId, imageUrl )
The function gets called on an on-click:
<area onclick="show360Simple('pContainer5','images/porch1.jpg');">
And I want to know how to end the function with another on-click:
<div id="close-div" onclick="what is the syntax here to end the above function?"></div>
Its probably simple but I'm a novice and haven't been able to work it out yet - any help is greatly appreciated - cheers.
The script linked above is using setTimeout to manage the animation.
To stop, you will need to modify the code a bit and add a stop function.
The simplest approach would be to store off the timeoutId returned from each setTimeout call. Then, in the stop function, call clearTimeout passing in the stored timeoutId.
Without making too many changes:
// Declare a global timeoutId
var timeoutId;
In function show360 change the setTimeout call to:
timeoutId = setTimeout(…);
In function move360 change the setTimeout call to:
timeoutId = setTimeout(…);
Then add a stop360 function:
function stop360() {
clearTimeout(timeoutId);
}
Demo fiddle
This will stop the animation - basically freezing it. If you want to remove the changes made by the script you could change the stop function to something like this:
function stop360(divContainerId) {
clearTimeout(timeoutId);
if(divContainerId) {
var o = document.getElementById(divContainerId);
o.style.backgroundImage = '';
o.style.position = "";
o.innerHTML = "";
}
}
Demo with Clear