How to call a function 10 seconds after calling another function? - javascript

I have two functions, functionOne() and functionTwo().
How can I go about calling functionTwo() 10 seconds after functionOne() ends/is called?
I'd like functionOne to occur after a button is clicked, and then functionTwo 10 seconds after functionOne ends (without the need to click a button again/have the user do anything!)!
See below for my code!
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
}
functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>
I tried to use setTimeout, but the problem is that I don't think there is an 'onend' event I can use for the first function. Eg:
setTimeout(functionOne.onend, 10,000);

This code calls functionOne onClick and calls functionTwo 10 seconds later.
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText" onClick="functionOne()">Click!</button>
<script>
function functionOne() {
document.getElementById("paragraphChange").innerHTML = "Bye World";
setTimeout(() => functionTwo(), 10000);
}
function functionTwo() {
document.getElementById("paragraphChange").innerHTML = "Jokes I'm still here";
}
</script>

Most importantly you have to declare your functions properly using the function keyword: function functionOne, function functionTwo.
Here's the documentation for setTimeout: "The global setTimeout() method sets a timer which executes a function... once the timer expires." So you pass in the function that you want to execute once the timer has completed.
And here are some more methods of approaching the problem.
Cache your paragraph element along with the button up front so you're making the code as DRY as possible.
Move the inline JS to the script, and use addEventListner to the para element
Use textContent instead of innerHTML because you're not adding HTML
// Cache the elements
const para = document.querySelector('#paragraphChange');
const button = document.querySelector('#clickToChangeText');
// Add a listener to the button
button.addEventListener('click', functionOne, false);
// Set the text content of the para element
// and then call the second function with a time out
function functionOne() {
para.textContent = 'Bye World';
setTimeout(functionTwo, 5000);
}
// Update the para with new text
function functionTwo() {
para.textContent = 'Jokes I\'m still here';
}
<p id="paragraphChange">"Hello World"</p>
<button type="button" id="clickToChangeText">Click!</button>

Define functionTow() first.
function functionTwo() {
//code to be execute
}
The call functionTwo in functionOne's body using setTimeout.
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}

I don't think there anything called onend in JavaScript you have to use setTimeout(functionTwo, 10000) at the end of functionOne() like this:
function functionTwo() {
//code to be execute
}
function functionOne(){
//code to be execute
//End of function
setTimeout(functionTwo, 10000);
}

Related

JS removeEventListener with function inside

I've created a function search with an event listener on a button. The problem is that the removeEventListener isn't working because init() is inside it to execute. Thus the EventListener is replicated everytime I click the button. If I remove init() all is fine. Maybe i misunderstand someting about it?
Also if i remove the function search and only use const I know it fires ones. But the whole point is that i need to use search.
function search(data) {
const clickHandler = () => {
console.log('search');
init();
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
}
search(data);
function init() {
console.log('hello');
}
console results:
first time; hello
second time; hello hello
third time; hello hello hello hello
The problem here is scoping. When you put the function inside another, it is scoped to that function. So next time you call the function, you create a new function. So you are trying to remove a function that did not exist before.
function clickHandler2() {
console.log('world');
}
function search() {
const clickHandler = () => {
console.log('hello');
};
document.getElementById('search').removeEventListener('click', clickHandler);
document.getElementById('search').addEventListener('click', clickHandler);
document.getElementById('search').removeEventListener('click', clickHandler2);
document.getElementById('search').addEventListener('click', clickHandler2);
}
search();
search();
search();
<button type="button" id="search">Search</button>

How do I trigger a javascript function if body is clicked after certain seconds?

I need to trigger a window.open function on the click of body, but only if the click is after few seconds.
EXAMPLE:- if the second click is done immediately, it shouldn't open the window. but after 5 seconds, if the click is made, the window should open.
My code isn't working.
<script>
setInterval(myadFunction,5000);
function myadFunction()
{
$("body").click(function () {
window.open("https://www.google.com");
});
}
</script>
This is a wordpress website., and I entered this code before <body> tag.
Why isn't it working?
You can use a flag to simulate what you want. In this case "canClick" flag will do the job for you.Reset it back to true after your desired timeout.
var canClick = true;
$("body").click(function () {
if (canClick) {
window.open("https://www.google.com");
canClick = false;
setTimeout(() => {
canClick = true
}, 5000);
}
});
Let me know if you face any issue with this snippet.
You could try something like:
<button onclick="timeFunction()">Submit</button>
<script>
function timeFunction() {
setTimeout(function(){ window.open("https://www.google.com"); }, 5000);
}
</script>
It consists of this:
setTimeout(functionname, milliseconds, arg1, arg2, arg3...)
The following are the parameters −
functionname − The function name for the function to be executed.
milliseconds − The number of milliseconds.
arg1, arg2, arg3: These are the arguments passed to the function.
First of all. You should make sure that you are placing the code in the right place. Since it's Wordpress. That bugger really get on my nerves. Try putting it in the active theme.
var click_allowed = 0; //global var (you use const if supported)
setTimeout(function(){ click_allowed = 1; },5000);
jQuery('body').click(function(){
if(click_allowed) window.open("https://www.google.com");
});
jQuery has been used instead of $ for the selectors due to wordpress native jquery limitation.
you can use settimeout(function, millisecond)

Change button onclick after first click

I'm having some struggles getting this to work.
I have a button, and I want it to execute Javascript function A, and in that function A, i want to change the Onclick to function B. Thus getting as result when the user taps the button a SECOND time, it's executing B. With the
<Button onclick="A();">Click me</button>
<script>
Function A() {
document.getElementById("button").onclick=B();
}
Function B() {
Alert("hello world");
}
In function A(), it doesn't execute FIRST A and after that B, it instantly executes B. Could anyone help me? Thanks :)
When you write a function name with the parenthesis, like B(), that invokes the function immediately. Instead, you'll want to set onclick to be just the name of the function, A or B.
Your overall solution could look something like this:
function A(event) {
// Function logic...
event.target.onclick = B;
}
function B() {
// Function logic...
}
document.getElementById("button").onclick = A;
You're calling B with B().
Use document.getElementById("button").onclick=B;. Note that there's no parentheses after B.
You can use Jquery to change any attribute of a button onclick. Below, I update the onclick attribute to instead execute function B()
function A() {
$('#toggler').attr('onclick', 'B()');
}
function B() {
console.log('Updated to B()!');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggler" onclick="A()">Click me!</button>
Use an id instead of the onclick for the button then target it from javascript like this:
function b()
{
console.log('I am in B.')
}
function a()
{
console.log('I am inside A.');
button1.removeEventListener('click', a);
button1.addEventListener('click', b);
}
var button1 = document.getElementById('button1'); // get the button element
button1.addEventListener('click',a); // assigns a click listener to a() at the beginning
<Button id="button1">Click me</button>

javascript onclick function does not run all code in function

This onClick function does not run the console.log in the code snippet below, any ideas?
var clickFunction = function myfunc() {
return function (){
return console.log('here');
}
};
<button onClick="clickFunction()"> Click here</button>
Thanks for your time
Because you're calling a function that returns a function. If you want to run the function that is returned you would need to do: clickFunction()()

setInterval is not working in YUI

I am trying to use SetInterval and clearInterval in YUI
The code is written so it will create element every second and on mouse hover of div it should stop creating element.
http://jsbin.com/awadek/5
Please let me know what is wrong with my code?
You should pass an anonymous function as a handler to "mouseover". Otherwise, Javascript will attempt to evaluate and call the return from clearInterval (in this case, an integer!). The following code will work:
YUI().use("console", "console-filters", "substitute", "node-event-simulate",
function(Y) {
console.log("YUI is ready");
var doSomething = function(e) {
Y.one("#seconds").append("<p>I am number four</p>");
};
IntervalId = setInterval(doSomething, 1000);
//Notice the anonymous function below:
Y.one("#clearInt").on('mouseover', function() { clearInterval( IntervalId ) });
});
Here is your JSBin, ftfy. Enjoy!

Categories

Resources