What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?
As always with Android there's lots of ways to do this, but assuming you simply want to run a piece of code a little bit later on the same thread, I use this:
new android.os.Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
public void run() {
Log.i("tag", "This'll run 300 milliseconds later");
}
},
300);
.. this is pretty much equivalent to
setTimeout(
function() {
console.log("This will run 300 milliseconds later");
},
300);
Android equivalent of setTimeout and clearTimeout of javascript?
According to the documentation of Handler
public final void removeCallbacks (Runnable r)
Added in API level 1
Remove any pending posts of Runnable r that are in the message queue.
Example code:
Runnable runnable = new Runnable() {
public void run() {
Log.i("Tag", "Runnable running!");
}
};
Handler handler = new android.os.Handler();
handler.postDelayed(runnable, 1000);
handler.removeCallbacks(runnable);
setInterval vs setTimeout which is better to run a loop at a specified speed
You can use async/await to emulate typing and create delays:
//
// Async timeout function
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));
//
// Bot typing function
const runBot = text => {
// Use promises
return new Promise(async (resolve, reject) => {
// DOM
const div = document.getElementById('text');
// Create chars array
const chars = text.split('');
// Wait 1 sec before typing
await timeout(1000);
// Type text
while(chars.length) {
// Put one char at iteration
div.innerHTML += chars.shift();
// Wait some amount
await timeout(100);
}
// Add new line to the text box
div.innerHTML += '<br>'
// Finish function
return resolve();
});
}
//
// Text typing runner and button controller
const typeText = async text => {
// DOM
const button = document.querySelector('button');
// Disable button
button.disabled = true;
// Run bot and wait till it finishes
await runBot(text);
// Enable button
button.disabled = false;
}
<div id="text" style="padding:10px;border:1px solid #000"></div>
<button onClick="typeText('This is demo text!')">Start bot</button>
JavaScript - Is it possible to modify the behaviour of setInterval/setTimeout used by third party scripts (externally hosted)
Well, I'd try to avoid this at all cost (except to try "for fun").
Here may be the result (a setInterval where all intervals >= 100 seconds are replaced by 100 seconds)
// above the use of setInterval by third party code
(function (w, maxVal) {
var f = w.setInterval;
w.setIntervalOld = f;
w.setInterval = function () {
var a = arguments;
if(a.length >= 2 && (a[1] > maxVal)) {
a[1] = maxVal;
}
f.apply(w, a);
};
})(window, 100000);
I tried to make the hack in the most coherent way and window.setIntervalOld is available for your own code. Tell me what it does for you.
Calling setInterval function inside a setTimeout method in java-script getting setInterval(...) is not a function error
your setinterval looks like
setInterval(fn, 300)()
... since setInterval
returns undefined
, this is what is not a function, and the cause of the error
i.e. setInterval is a function, but what it returns is not - simply remove the ()
after , 300)
function runEvery300Milli(){
var t = new Date();
window.setInterval(function(){
if((t.getMinutes===59 && t.getMilliseconds>499)||(t.getMinutes===0 && t.getMilliseconds<500)){
console.log(t.getMinutes()+ ":"+t.getSeconds() + ":"+ t.getMilliseconds());
}
}, 300); // <=== removed trailing ()
}
How to implement the javascript setTimeout function in Java
Create a Handler
and use .postDelayed(..)
to run a background task after some delay.
If user presses the key then call handler.removeCallback(..)
and then again .postDelayed(..)
to add a new delayed callback.
Related Topics
Why Can't I Use Resources.Getsystem() Without a Runtime Error
Why Do We Have to Call Super in Android Sometimes
Custom Progress Bar in Android
Android Webview Always Returns Null for JavaScript Getelementbyid on Loadurl
Values of Counter Changes After Scrolling Expendablelistview
How Run Cookbook with Dependencies in Chef
Networksecurityconfig: No Network Security Config Specified -- Android 7.0 Error
Reducing Android App (Apk) Size
Android: Changing Background-Color of the Activity (Main View)
Google Cloud Messaging: Don't Receive Alerts When iOS App Is in Background
How to Get from Jruby a Correctly Typed Ruby Implementation of a Java Interface
Spark: How to Map Python with Scala or Java User Defined Functions