Javascript - setTimeout - javascript

I am learning Javascript right now. I have a small issue that I can't figure out how to solve it. I would like to clear content of my html page after my function displayed "Hi hi" in web page.
<html>
<body onload="alertFunc()">
<script>
function alertFunc() {
var statement = "Hi hi"
for (let i = 0; i < statement.length; i++) {
let c = statement.charAt(i);
setTimeout(function(){
document.write(c);
},i * 1000);
}
}
</script>
</body>
</html>

try this to clear content of your site after 1 second
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Learning </title>
</head>
<body>
<script>
document.write('hi hi');
function alertFunc() {
setTimeout(function(){
document.write(' ');
}, 1000);
}
alertFunc();
</script>
</body>
</html>
if you want to change content with time again and again then you have to use setInterval

Related

Loop blocks DOM Manipulation

I have a simple counting loop that counts to 10000 and logs every number to the console. Before i start the loop i want to write "TEST" to the body in my html.
Although i do this before i start the loop it appends "TEST" to the body only after the loop is done. However i can log something to the console before starting the loop. I think i am blocking the browser thread or something, i don't know how to write this in a non blocking manner. I have been trying to figure out this Problem for quite some time. Your Help would be much appreciated !!!
My HTML code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button onclick="myfunc()">click me</button>
</body>
<script src="index.js"></script>
</html>
My javascript code:
function myfunc() {
var h1 = document.createElement("h1").innerText = "TEST"
document.body.appendChild(h1) //appends only after loop is done
console.log("test") // this works
for (var i = 0; i < 10000; i++){
console.log(i)
}
}
One solution is to put your loop code in a timeout and set the delay to 1 millisecond
function myfunc() {
var h1 = document.createElement("h1")
h1.innerText = "TEST"
document.body.appendChild(h1) //appends before the loop
console.log("test") // this works
setTimeout(()=>{
for (var i = 0; i < 10000; i++){
console.log(i)
}
},1)
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button onclick="myfunc()">click me</button>
</body>
<script src="index.js"></script>
</html>

How to pass on dynamic delay to d3.interval

d3.interval takes two parameters, callback and delay,e.g.
d3.interval(callback, delay).
I was wondering if it is possible to pass on a dynamic delay for each interval.
For example, in the following, I am asking the interval to run at 1000ms delay. But is there a way I can ask d3.interval to run at 0ms, 1000ms, 2000ms, 3000ms respectively for interval# 1,2,3,4.
I tried like desiredDelay[counterF] but it did not work.
const masterSelection = d3.selectAll('[class^="text"]');
const node = masterSelection.nodes();
const len = node.length - 1;
let counterF = 0;
const del = 1000;
const desiredDelay = [0, 1000, 2000, 3000]
let ticker = d3.interval(
e => {
const element = masterSelection['_groups'][0][counterF];
const selection = d3.select(element).node();
console.log(selection);
counterF++;
(counterF > len) ? ticker.stop(): null
}, del
)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<div class='text1'>one</div>
<div class='text2'>two</div>
<div class='text3'>three</div>
<div class='text4'>four</div>
</body>
<script type="text/javascript" src="prod.js"></script>
</html>
Short answer: you can't.
If you look at the source code you'll see that if the delay is not null...
if (delay == null) return t.restart(callback, delay, time), t;
...it will be coerced to a number using the unary plus operator:
t.restart = function(callback, delay, time) {
delay = +delay,
etc...
What you can do is creating your own interval function, which is out of the scope of this answer.
Adapted from this, the following works as desired and is to be used with d3.timeout.
const masterSelection = d3.selectAll('[class^="text"]');
const node = masterSelection.nodes();
const len = node.length - 1;
let counter = 0;
//const del = 1000;
const delay = [0, 1000, 2000, 3000];
function show() {
const element = masterSelection["_groups"][0][counter];
const selection = d3.select(element).node();
console.log(selection);
counter++;
if (counter > len) return
d3.timeout(show, delay[counter]);
}
show();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script type="text/javascript" src="https://d3js.org/d3.v7.min.js"></script>
<body>
<div class='text1'>one</div>
<div class='text2'>two</div>
<div class='text3'>three</div>
<div class='text4'>four</div>
</body>
<script type="text/javascript"></script>
</html>

Audio() tag in JavaScript

My code is as follows, but not executable!
And anything that clicks on the play button doesn't run
HTML:
<button id="play"><img id="playicon" src="img/Polygon 1.svg"></button>
JS:
'song0' is a variable sound and sounds in 'playPauseEvent' and out of function but does not work in performance, I found this method on the following site
https://www.developphp.com/video/JavaScript/Audio-Seek-and-Volume-Range-Slider-Tutorial
var playpause, play1icon, song0;
function aslekar(){
song0 = new Audio('audio/Meydoon.mp3');
song0.loop = true;
song0.play();
document.getElementById("moon");
play1icon = document.getElementById("playicon");
playpause = document.getElementById("play");
playpause.addEventListener("click", playPauseEvent);
function playPauseEvent(){
if(song0.paused){
song0.play();
play1icon.setAttribute("src", "img/Polygon 1.svg");
}else{
song0.pause();
play1icon.setAttribute("src", "img/Group 1.svg");
}
}
}
window.addEventListener("load", aslekar);
I am very beginner and hope you can help with this :)
Check this
Live Preview
var playpause, play1icon, song0;
function aslekar(){
song0 = new Audio('https://gamepedia.cursecdn.com/dota2_gamepedia/d/db/Vo_crystalmaiden_cm_kill_07.mp3');
song0.loop = true;
song0.play();
document.getElementById("moon");
play1icon = document.getElementById("playicon");
playpause = document.getElementById("play");
playpause.addEventListener("click", playPauseEvent);
function playPauseEvent(){
if(song0.paused){
song0.play();
play1icon.setAttribute("src", "https://image.flaticon.com/icons/svg/64/64485.svg");
}else{
song0.pause();
play1icon.setAttribute("src", "https://image.flaticon.com/icons/svg/27/27223.svg");
}
}
}
window.addEventListener("load", aslekar);
and the html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<button id="play" onclick="playPauseEvent()"><img id="playicon" src="https://image.flaticon.com/icons/svg/27/27223.svg" width="30" height="30"></button>
</body>
</html>

How do I show timer on click of link?

So if you notice I have created a link in the preview below. What I'm looking for is if someone clicks on the link. I want to replace the text for a 60 seconds timer, and once the 60 seconds are finished, the text and link should reappear, and the same process continues.
Can someone help?
Request code again
You can use javascript setInterval and then clearInterval for this.
Your code while using jQuery should look like this: (change the value of timer_output_initial to time in number of seconds you want)
var display_timer_interval;
var timer_output_initial = 5
var timer_output = timer_output_initial;
var initial_text = "";
$("#timer_link").on("click",function(){
var clicked_element = $(this);
initial_text = clicked_element.html();
display_timer_interval = setInterval(function(){
display_time(clicked_element);
}, 1000);
});
function display_time(element){
timer_output = timer_output-1;
if(timer_output === 0) {
clearInterval(display_timer_interval);
timer_output = timer_output_initial;
element.html(initial_text);
}else{
$(element).html(timer_output);
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
Request code again
</body>
</html>

Display the result of a function as variable in a browser using document.getElementbyId.innerHTML in JavaScript

I am a newbie to JavaScript < 1 Week old
I wrote a very short HTML/JavaScript and got it to display on console.
Basically, I want to display the result of a function used as a variable inside the <p> tag of the HTML.
I got the script to display in the console.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
</script>
<script>
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
</script>
<p id="Kilograms"><!--I want the result here--></p>
</body>
</html>
How do I get the result of the function as a variable i.e var kilo (pounds)... to display in the p tag with id Kilograms?
Script shold be after BODY code, or you should add document ready event listener. So, try this solution:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<p id="Kilograms"><!--I want the result here--></p>
</body>
<script>
var kilo = function(pound) {
return pound/2.2;
}
kilo (220);
console.log (kilo(220));
var kilog = function(pounds) {
return pounds/2.2;
}
console.log (kilog(440));
document.getElementById("Kilograms").innerHTML = kilog(440);
</script>
</html>
Example in JSBin: https://jsbin.com/pacovasuve/edit?html,output
You can try this in your js code.
document.getElementById("Kilograms").innerHTML="write whatever you want here";
Try this
var p = document.getElementById('Kilograms');
p.innerHtml = 'any text';
// OR
p.innerHtml = kilog(440);

Categories