setTimeout() not working in return value - javascript

I have add setTimeout but it's not working. I want to show question after 5 sec of the end of the sound.
self.getQuestionText = function() {
startSound('levelq', false);
setTimeout(function() {
return self.questions[self.level() - 1].question;}, 5000);
}

setTimeout() in asynchronous and returns the value in the callback function. Change the structure of your js.
Instead of:
self.getQuestionText = function () {
startSound('levelq', false);
setTimeout(function () {
return self.questions[self.level() - 1].question;
}, 5000);
}
// The rest of the code
Use callback structure:
self.getQuestionText = function () {
startSound('levelq', false);
setTimeout(function () {
self.getQuestionText = self.questions[self.level() - 1].question;
// The rest of the code
}, 5000);
}

Related

Unable to reset setTimeout timer in JavaScript

Here is my pseudocode:
if(key.pressed = 'a') {
activate = true;
}
var mytimeout = function timer_function() {
// Do stuff;
setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(mytimeout);
timer_function();
}
}
if(mouse.click == true) {
some_function();
}
I want the timer to be reset on each mouse click which calls some_function(). What actually happens is that the time is set on first click but never resets after that.
What am I missing?
Thanks.
mytimeout is a function, not a timeout handle. What you need to store is the result of the setTimeout call like this.
var timeoutHandle;
function timer_function() {
// Do stuff;
timeoutHandle = setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(timeoutHandle);
timer_function();
}
}
In function timer_function return the value of setTimeout
var mytimeout = function timer_function() {
return setTimeout( function() {
//Do some more stuff
}, 5000);
}
Thats because in you are only going to replay the Timeout only when the user presses the "a" key. I don't know why you kept it like that but thats probably the reason.!

Dynamically added function still running even after remove from DOM

This script has been added dynamically. It has a timeout function, means that it runs every 5 seconds.
dynamicjs.php
$(document).ready(function(){
(function( $ ){
$.fn.baslatmesajlari = function() {
setInterval(function(){
console.log("I am running");
}, 5000);
return this;
};
})( jQuery );
});
$("body").baslatmesajlari();
I load this function to a div using;
$("#temporarycontent").load("dynamicjs.php");
And when I do
$("#temporarycontent").empty();
The script is still running. How can I stop it run ?
You can't, you need a handle to the intervalId returned by the setInterval function or provide an API on the plugin in order to destroy it and cleanup after itself. The easiest way would be to attach the state of the plugin to the DOM element on which it was applied.
(function ($) {
const PLUGIN_NAME = 'baslatmesajlari';
function Plugin($el) {
this.$el = $el;
this._timerId = setInterval(function () {
console.log('running');
}, 2000);
}
Plugin.prototype.destroy = function () {
this.$el.removeData(PLUGIN_NAME);
clearInterval(this._timerId);
};
$.fn[PLUGIN_NAME] = function () {
if (!this.data(PLUGIN_NAME)) this.data(PLUGIN_NAME, new Plugin(this));
return this;
};
})(jQuery);
$(function () {
var plugin = $('#plugin').baslatmesajlari().data('baslatmesajlari');
$('#destroy').click(function () {
plugin.destroy();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="plugin"></div>
<button id="destroy">Destroy plugin</button>
You must have a reference to the interval id, then, when you want to stop it's execution, call clearInterval(the_id)
let interval = null //this is the variable which will hold the setInterval id
$(document).ready(function () {
(function ($) {
$.fn.baslatmesajlari = function() {
interval = setInterval(function () {
console.log('I am running')
}, 5000)
return this
}
})(jQuery)
})
$("body").baslatmesajlari()
And then:
$("#temporarycontent").empty();
clearInterval(interval) // it should stop the function.
Hope it helps.

How can I stop custom jQuery function which is running?

I have a custom jQuery function. When it runs every 5 seconds.
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 5000);
}
return this;
};
})(jQuery);
$("#container").mycustomfunction();
I have a
clearInterval(interval);
to stop, but I also want to stop the function completely. How can I do that ?
Functions you add to this object will be attached to your object and Simple and naive solution will follow:
(function($) {
$.fn.mycustomfunction = function() {
interval = setInterval(function() {
console.log("I am running every 5 seconds");
}, 1000);
this.stop= function(){
clearInterval(interval);
}
// another function
this.alert = function(msg){
alert(msg)
}
return this;
};
})(jQuery);
to stop use
var feature = $("#container").mycustomfunction();
feature.stop();

Successive setTimout() calls all execute at once

setTimeout(thisFunc, 500);
setTimeout(thatFunc, 500);
setTimeout(otherFunc, 500);
finalFunc();
What I expect is thisFunc(), followed by a half second pause, then thatFunc() followed by a half second pause, then otherFunc(), followed by a pause. Then finalFunc().
What actually happens, is the page pauses for 1 1/2 seconds then all four functions seem to execute at once.
How can I achieve the pause I am after? It's being done purely for aesthetical purposes in the UI.
You can use the callbacks too if you need to use 500 ms as a variable for example:
var timeout = 500;
setTimeout(function() {
thisFunc();
setTimeout(function() {
thatFunc();
setTimeout(function() {
otherFunc();
}, timeout);
}, timeout);
}, timeout);
An alternate way would be:
setTimeout(thisFunc, 500);
function thisFunc () {
/* ...whatever... */
setTimeout(thatFunc, 500);
}
function thatFunc () {
/* ...whatever... */
setTimeout(otherFunc, 500);
}
function otherFunc () {
/* ...whatever... */
setTimeout(finalFunc, 500);
}
function finalFunc () {
/* ...whatever... */
}
Try to give the delay properly,
setTimeout(thisFunc, 500);
setTimeout(thatFunc, 1000);
setTimeout(otherFunc, 1500);
setTimeout(finalFunc, 2000);
If you give 500 ms for all the setTimeouts, then every thing would be fired at a same time.
And the best approach would be,
var func = function(func){ func(); }
function setContinuos() {
var funcs = Array.from(arguments);
var delay = funcs.pop();
funcs.forEach(function(itm, index) {
setTimeout(function() {
func(itm);
}, (index + 1) * delay)
});
}
setContinuos(func1,func2,func3,func4,500);
DEMO

why setTimeout() only run my code once,at first time? [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 8 years ago.
i use this javascript code to open two pictures and toggle a vertical menu by clicking on another picture. an know i want to run code without clicking on image, with a timer. so i wrote this code but it run only once at first time.
what's wrong with my code?
<script type="text/javascript">
$(document).ready(function () {
$("#lista2").slideToggle(1);
$curtainopen = false;
$(".rope").click(function () {
$(this).blur();
if ($curtainopen == false) {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-on.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '-120px' }, 2000);
$(".rightcurtain").stop().animate({ left: '120px' }, 2000);
$("#R").attr('src', 'images/Right.gif');
$("#L").attr('src', 'images/Left.gif');
$curtainopen = true;
$("#lista2").slideToggle(2000);
$(this).attr('id', '1');
} else {
var selected = $(this).val();
var image = $(".rope");
image.fadeOut('fast', function () {
$("#largeImg").attr('src', 'images/power-off.png');
image.fadeIn('fast');
});
$(".leftcurtain").stop().animate({ left: '0px' }, 2000);
$(".rightcurtain").stop().animate({ left: '0px' }, 2000);
$curtainopen = false;
$("#lista2").hide();
$(this).attr('id', '0');
}
return false;
});
});
function startTimer() {
setTimeout($(".rope").click(), 4000);
}
</script>
use this to execute your code after a specific time interval
setInterval(function() {
$(".rope").click(); // this will execute after every 4 sec.
}, 4000);
use this to execute your code after a specific time delay
setTimeout(function() {
$(".rope").click(); // this will execute after 4 sec delay only once.
}, 4000);
use above according to your requirement
setTimeout need a function, When you are passing $(".rope").click() it is called immediately.
Use it like
function startTimer() {
setTimeout(function () {
$(".rope").click();
}, 4000);
}
setTimeout(function() {
$(".rope").click();
}, 4000);
because setTimeout needs a function, but $(".rope").click() calls itself immediatly (instead of assigning a function to be called). So you don't want to call a function but to pass it to setTimeout.
A timer implies repeating the function after each timeout. setTimeOut only delays a function once (after a given time, in milliseconds).
function startTimer() {
//do your stuff
$(".rope").click();
//repeats itself after 4 seconds
setTimeout(startTimer, 4000);
}
And do not forget to start it on document ready :
$(document).ready(function () {
startTimer();
...
}
I you don't want your function to be called immediately on page load, you can add an initial delay :
$(document).ready(function () {
setTimeout(startTimer, 5000); //the timer will start only 5 seconds after page load
...
}

Categories

Resources