[英]Make a js function wait for an event listener
Here the problem.这里的问题。 I have a script that collects images from the web in a "for" cycle to append them in the body.
我有一个脚本,它在“for”循环中从 web 收集图像,然后将它们放入体内。 When the script links the img to its source, I introduce a script to change the source to a new one based on an event listener.
当脚本将 img 链接到它的源时,我引入了一个脚本来根据事件侦听器将源更改为新的。
In other word, I want to wait for the event listener to go back and finish the iteration.换句话说,我想等待 go 的事件侦听器返回并完成迭代。
I was thinking to use a globar var to share the information between the listener and the script.我正在考虑使用 globar var 在侦听器和脚本之间共享信息。
function UseNewSource(input) {
console.log("wait to change " + input);
!!! wait for a listener that does not go on with the code !!!
newSource = global_var
return newSource
}
document.getElementById('passbtn').addEventListener('click', function () {
console.log('clicked !!!');
global_var = "something"
});
You can use this snippet.您可以使用此代码段。 Whenever the image is ready, the dom-manipulation code will be executed.
每当图像准备好时,就会执行 dom 操作代码。 But it wouldn't be serially.
但它不会是连续的。 Cause if any image that has a big size, then it will take longer time than others.
因为如果任何图像的尺寸很大,那么它会比其他图像花费更长的时间。 But I don't think it will be an issue.
但我不认为这将是一个问题。 You can check the output of the console log.
可以查看控制台日志的output。 Thank you.
谢谢你。
const fetchImage = async (url) => { const img = await fetch(url).then(response => response.json()); // Do the dom operation here console.log(img); } for(let i = 1; i<=10; i++) { fetchImage(`https://jsonplaceholder.typicode.com/photos/${i}`); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.